-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJDBCUtil.java
More file actions
86 lines (77 loc) · 2.11 KB
/
JDBCUtil.java
File metadata and controls
86 lines (77 loc) · 2.11 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
package Util;
import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
public class JDBCUtil {
private static String driver="com.mysql.jdbc.Driver";
private static String url="jdbc:mysql://localhost:3306/jspdemo?useUnicode=true&characterEncoding=utf8";
private static String user="root";
private static String password="787913269";
static Connection conn = null;
static {
/*
* Properties properties = new Properties(); // 创建一个properties对象 Reader
* inReader; // 一个reader属性;
*
* try { String path =
* Thread.currentThread().getContextClassLoader().getResource("jdbc.properties")
* .getPath(); inReader = new FileReader(path); // 用这个方法获取properties配置文件;
* properties.load(inReader); // 加载load内部的地址; } catch (Exception e) { // TODO
* Auto-generated catch block e.printStackTrace(); }
*/
// 通过properties.getProperty("driver");方法获取值
/*
* driver = properties.getProperty("driver"); url =
* properties.getProperty("url"); user = properties.getProperty("user");
* password = properties.getProperty("password");
*/
}
/**
* 打开数据库连接
*
* @return
*/
public static Connection open() {
try {
Class.forName(driver);
System.out.println("连接成功......");
return DriverManager.getConnection(url, user, password);
} catch (Exception e) {
System.out.println("连接数据库失败....");
}
return null;
}
/**
* 关闭数据库连接
*
* @return
*/
public static void close(Connection con,PreparedStatement ps,ResultSet rs) {
if (conn != null) {
try {
conn.close();// 关闭数据库
System.out.println("关闭...");
} catch (Exception e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();// 关闭数据库
} catch (Exception e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
ps.close();// 关闭数据库
} catch (Exception e) {
e.printStackTrace();
}
}
}
}