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; //數(shù)據(jù)庫(kù)連接對(duì)象
17 private Statement stmt = null; //數(shù)據(jù)庫(kù)sql語(yǔ)句對(duì)象
18 private ResultSet rs = null; //數(shù)據(jù)庫(kù)結(jié)果集對(duì)象
19
20 private static final String DRIVER="com.mysql.jdbc.Driver";//這是一個(gè)連接數(shù)據(jù)庫(kù)必填的常量
21 private static final String URL = "jdbc:mysql://localhost:3308/shxt"; //數(shù)據(jù)庫(kù)的URL 3308為端口 shxt是那個(gè)數(shù)據(jù)庫(kù)
22 private static final String USER = "root"; //數(shù)據(jù)庫(kù)的賬號(hào)
23 private static final String PWD = "mysql"; //數(shù)據(jù)庫(kù)的密碼
24
25 private static DBUtil db=null;
26
27 public static DBUtil getDB() {
28 //判斷是否為空,這樣的方式更加節(jié)省資源
29 if(db == null) {
30 db = new DBUtil();//實(shí)例化對(duì)象
31 }
32 return db;
33 }
34 //將構(gòu)造器隱藏,這樣就無(wú)法調(diào)用構(gòu)造器
35 private DBUtil() {
36 //................
37 }
38
39
40 //獲得數(shù)據(jù)庫(kù)連接,加載驅(qū)動(dòng)
41 public static Connection getConn() {
42 //加載驅(qū)動(dòng)
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 }
? 來(lái)源:https://www./content-4-277351.html
|