jdbc连接第三种方法:

//jdbc第五种连接方式-----------------------------------------------------------------
//前戏:导入c3p0、mchange的jar包,还有c3p0-config的xml文件
private Connection con;

public Connection getCon(){
//直接得到数据源吧(参数就是第一个标签的name属性)
ComboPooledDataSource dataSource = new ComboPooledDataSource(“mysqlConfig”);
try {
//得到连接
con = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}

//返回增删改结果集的方法(int)
public int methodUtils(String sql,Object[] obj){
int num = 0;
try {
PreparedStatement preparedStatement = getCon().prepareStatement(sql);
if(obj!=null&&obj.length!=0){
for (int i = 0; i <obj.length ; i++) {
preparedStatement.setObject(i+1,obj[i]);
}
}
num = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return num;
}

//得到返回查询结果集的方法(ReturnResult)
public ResultSet getAll(String sql, Object[] obj){
ResultSet rs = null;
try {
PreparedStatement preparedStatement = getCon().prepareStatement(sql);
if(obj!=null&&obj.length!=0){
for (int i = 0; i <obj.length ; i++) {
preparedStatement.setObject(i+1,obj[i]);
}
}
rs = preparedStatement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}

//关闭所有连接对象的方法
public void doClose(ResultSet rs,PreparedStatement ps,Connection con) {
//从后关到前
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}

如需要前戏的资源请留言拿哈!

猜你喜欢

转载自blog.csdn.net/weixin_42334396/article/details/83306114