JAVA操作mysql数据库

来源:互联网 发布:淘宝鞋子买大了怎么换 编辑:程序博客网 时间:2024/05/18 00:37
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;    }}
0 3