Repository navigation
Expand file tree
/
Copy pathDBUtil.java
More file actions
109 lines (102 loc) · 3.54 KB
/
Copy pathDBUtil.java
File metadata and controls
109 lines (102 loc) · 3.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package com.test.basic.chapter8;
import java.sql.*;
/**
* Created by beigui on 2016/2/23.
* 把数据库操作放到这个工具类中,直接进行操作
*/
public class DBUtil {
private static Connection conn = null;
private static PreparedStatement preStatement = null;
private static ResultSet rs = null;
//获取连接。饿汉式 推荐 。懒汉式就是在构造时连接上,然后方法返回connection。
public static Connection getConnection(String driver, String url, String username, String password) {
try {
if (null == conn || conn.isClosed()) {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
}
} catch (ClassNotFoundException cex) {
cex.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//关闭连接。在不用数据库时,要关闭连接。
public static void close() {
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//查询方法,打印出结果集
public static void query(String sql) {
if (null == conn) {
return;
}
try {
preStatement = conn.prepareStatement(sql);
rs = preStatement.executeQuery();
//获取列数
int columns = rs.getMetaData().getColumnCount();
int rows = 1;
//循环一组一组取结果集
while (rs.next()) {
System.out.println("第" + rows + "行:");
//按列下标取出某行某列的数据
for (int i = 1; i < columns; i++) {
System.out.println("第" + i + "列数据:" + rs.getString(i));
}
rows++;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//最终别忘了做关闭操作
if (null != rs) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (null != preStatement) {
try {
preStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
//插入或者是更新。插入或者更新都是executeUpdate(),同时设置参数值的方法也一样
// params是一个不定长度的字符串数组,相当于String[] params
public static void insertOrUpdate(String sql, String... params) {
if (null == conn) {
return;
}
try {
preStatement = conn.prepareStatement(sql);
int i = 1;
//设置参数值。这个写法相当于for(int i = 0; i < params.length; i++) {String item = params[i];}
for (String item : params) {
preStatement.setString(i++, item);
}
System.out.println("插入记录结果:" +preStatement.executeUpdate());
} catch (SQLException e) {
e.printStackTrace();
} finally {
//别忘了关闭
if (null != preStatement) {
try {
preStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}