JAVA操作mysql数据库

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
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值