您的位置:首页 > 编程语言 > Java开发

JAVA操作mysql数据库

2016-04-11 15:50 435 查看
package oa.api.all;

import java.io.FileNotFoundException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONObject;
import oa.api.all.Config;

//操作数据库
public class Database {
private Config cf = new Config();
private List<String> result = new ArrayList<String>();
private Connection conn;
//jdbc连接mysql,返回连接字符串;连接信息从配置文件读取;
private String get_mysql_url() throws FileNotFoundException{
String api_login_database = cf.get_config("api_login_database");
String mysql_host = cf.get_config("mysql_host");
String mysql_user = cf.get_config("mysql_user");
String mysql_password = cf.get_config("mysql_password");
String mysql_port = cf.get_config("mysql_port");
String mysql_url = "jdbc:mysql://"+mysql_host+":"+mysql_port+"/"+api_login_database+"?user="+mysql_user+"&password="+mysql_password;
return mysql_url;
}
//查询mysql,返回查询结果list;
public List<String> select_from_mysql(String sql) throws SQLException, FileNotFoundException{
String mysql_url = get_mysql_url();
conn = DriverManager.getConnection(mysql_url);
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
ResultSetMetaData rm = rs.getMetaData();
while(rs.next()){
JSONObject json_obj = new JSONObject();
for (int i=1; i<=rm.getColumnCount(); i++){
json_obj.put(rm.getColumnLabel(i), rs.getString(i));
}
result.add(json_obj.toString());
}
rs.close();
conn.close();
return result;
}
//操作mysql,包括update、delete、insert
public int update_from_mysql(String sql) throws FileNotFoundException, SQLException{
int affect_row;
String mysql_url = get_mysql_url();
conn = DriverManager.getConnection(mysql_url);
PreparedStatement ps = conn.prepareStatement(sql);
affect_row = ps.executeUpdate();
return affect_row;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: