1 package jdbcDome; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.sql.Statement; 8 9 /** 10 * JDBC工具類 11 * @author sunjian 12 * 13 */ 14 public class DBUtil { 15 16 private static Connection conn = null; //數據庫鏈接對象 17 private Statement stmt = null; //數據庫sql語句對象 18 private ResultSet rs = null; //數據庫結果集對象 19 20 private static final String DRIVER="com.mysql.jdbc.Driver";//這是一個鏈接數據庫必填的常量 21 private static final String URL = "jdbc:mysql://localhost:3308/shxt"; //數據庫的URL 3308爲端口 shxt是那個數據庫 22 private static final String USER = "root"; //數據庫的帳號 23 private static final String PWD = "mysql"; //數據庫的密碼 24 25 private static DBUtil db=null; 26 27 public static DBUtil getDB() { 28 //判斷是否爲空,這樣的方式更加節省資源 29 if(db == null) { 30 db = new DBUtil();//實例化對象 31 } 32 return db; 33 } 34 //將構造器隱藏,這樣就沒法調用構造器 35 private DBUtil() { 36 //................ 37 } 38 39 40 //得到數據庫鏈接,加載驅動 41 public static Connection getConn() { 42 //加載驅動 43 try { 44 Class.forName(DRIVER); 45 try { 46 conn=DriverManager.getConnection(URL, USER, PWD); 47 } catch (SQLException e) { 48 // TODO Auto-generated catch block 49 e.printStackTrace(); 50 } 51 } catch (ClassNotFoundException e) { 52 e.printStackTrace(); 53 } 54 return conn; 55 } 56 57 //處理增刪改sql的方法 58 public int update(String sql) { 59 int num = 0; 60 conn=getConn(); 61 try { 62 stmt=conn.createStatement(); 63 num = stmt.executeUpdate(sql); 64 } catch (SQLException e) { 65 e.printStackTrace(); 66 } 67 return num; 68 } 69 70 //處理查詢sql的方法 71 public ResultSet query(String sql) { 72 conn=getConn(); 73 try { 74 stmt=conn.createStatement(); 75 rs=stmt.executeQuery(sql); 76 } catch (SQLException e) { 77 e.printStackTrace(); 78 } 79 return rs; 80 } 81 82 //釋放資源的方法 83 public void close() { 84 try { 85 if(rs != null) { 86 rs.close(); 87 } 88 89 if(stmt != null) { 90 stmt.close(); 91 } 92 93 if(conn != null) { 94 conn.close(); 95 } 96 } catch (SQLException e) { 97 e.printStackTrace(); 98 } 99 } 100 }