MySQL操作类(本人自己写的)

时间:2022-12-11 14:52:31
 package com.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
public class DBUtil { //定义连接数据库需要的
Connection ct=null;
PreparedStatement pS=null;
ResultSet rS=null;
private static String url = "jdbc:mysql://"+DBSomeType.MYSQLURL+":3306/weixin?characterEncoding=UTF-8&autoReconnect=true";
private static String driverName = "com.mysql.jdbc.Driver"; /**
* 数据库查询,本操作查询完需手动关闭连接
* @param sql
* @param params
* @return 查询结果ResultSet
*/
public ResultSet getSlect(String sql,Object ...params){
Vector rowDate=new Vector();
Vector columnDate =new Vector();
try {
ct = connectWithDB();
pS=ct.prepareStatement(sql);
for(int i = 0;i < params.length;i++){
pS.setObject(i+1, params[i]);
}
rS=pS.executeQuery();
} catch (Exception e) {
// TODO: handle exception
}finally{
return rS;
}
} /************修改数据库操作*********************/
public int update(String sql,Object ...params){
int executeUpdate_int = 0;
try {
ct = connectWithDB();
pS=ct.prepareStatement(sql);
for(int i = 0;i < params.length;i++){
pS.setObject(i+1, params[i]);
}
//执行操作
executeUpdate_int = pS.executeUpdate();
System.out.println("executeUpdate_int = "+executeUpdate_int);
} catch (Exception e) {
// TODO: handle exception
}finally{
shutDownDB();
return executeUpdate_int;
}
} /************连接数据库*********************/
private Connection connectWithDB(){
Connection connection = null;
try {
Class.forName(driverName);
connection= DriverManager.getConnection(url, DBSomeType.ROOTUSERNAME, DBSomeType.ROOTPASSWORD);
} catch (Exception e) {
// TODO: handle exception
}
return connection;
} /************关闭数据库的相关连接*********************/
public void shutDownDB(){
try
{
if(rS!=null) rS.close();
if(pS!=null) pS.close();
if(ct!=null) ct.close();
} catch (Exception e2)
{
e2.printStackTrace();
// TODO: handle exception
}
} }