1 package com.test; 2 import java.sql.Connection; 3 import java.sql.DriverManager; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.util.Vector; 7 public class DBUtil { 8 9 //定义连接数据库需要的 10 Connection ct=null; 11 PreparedStatement pS=null; 12 ResultSet rS=null; 13 private static String url = "jdbc:mysql://"+DBSomeType.MYSQLURL+":3306/weixin?characterEncoding=UTF-8&autoReconnect=true"; 14 private static String driverName = "com.mysql.jdbc.Driver"; 15 16 /** 17 * 数据库查询,本操作查询完需手动关闭连接 18 * @param sql 19 * @param params 20 * @return 查询结果ResultSet 21 */ 22 public ResultSet getSlect(String sql,Object ...params){ 23 Vector rowDate=new Vector(); 24 Vector columnDate =new Vector(); 25 try { 26 ct = connectWithDB(); 27 pS=ct.prepareStatement(sql); 28 for(int i = 0;i < params.length;i++){ 29 pS.setObject(i+1, params[i]); 30 } 31 rS=pS.executeQuery(); 32 } catch (Exception e) { 33 // TODO: handle exception 34 }finally{ 35 return rS; 36 } 37 } 38 39 /************修改数据库操作*********************/ 40 public int update(String sql,Object ...params){ 41 int executeUpdate_int = 0; 42 try { 43 ct = connectWithDB(); 44 pS=ct.prepareStatement(sql); 45 for(int i = 0;i < params.length;i++){ 46 pS.setObject(i+1, params[i]); 47 } 48 //执行操作 49 executeUpdate_int = pS.executeUpdate(); 50 System.out.println("executeUpdate_int = "+executeUpdate_int); 51 } catch (Exception e) { 52 // TODO: handle exception 53 }finally{ 54 shutDownDB(); 55 return executeUpdate_int; 56 } 57 } 58 59 /************连接数据库*********************/ 60 private Connection connectWithDB(){ 61 Connection connection = null; 62 try { 63 Class.forName(driverName); 64 connection= DriverManager.getConnection(url, DBSomeType.ROOTUSERNAME, DBSomeType.ROOTPASSWORD); 65 } catch (Exception e) { 66 // TODO: handle exception 67 } 68 return connection; 69 } 70 71 /************关闭数据库的相关连接*********************/ 72 public void shutDownDB(){ 73 try 74 { 75 if(rS!=null) rS.close(); 76 if(pS!=null) pS.close(); 77 if(ct!=null) ct.close(); 78 } catch (Exception e2) 79 { 80 e2.printStackTrace(); 81 // TODO: handle exception 82 } 83 } 84 85 }