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;
}
}
JAVA操作mysql数据库
最新推荐文章于 2016-04-16 20:30:31 发布