-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathJDBCUtil.java
More file actions
69 lines (69 loc) · 1.23 KB
/
JDBCUtil.java
File metadata and controls
69 lines (69 loc) · 1.23 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
package myjava;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public final class JdbcUtils//不允许继承
{
private static String url = "jdbc:mysql://localhost:3306/demo";//连接地址
private static String user = "root";//用户名
private static String password = "root";//密码
private JdbcUtils(){};//禁止创建对象不允许继承
static//静态代码块,保证了驱动只注册一次
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e)
{
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws SQLException//获取建立了连接的对象
{
return DriverManager.getConnection(url,user,password);
}
public static void free(ResultSet rs,Statement st,Connection conn)//关闭资源
{
try
{
if(rs != null)
{
rs.close();
}
}
catch(SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
if(st != null)
{
st.close();
}
}
catch(SQLException e)
{
e.printStackTrace();
}
finally
{
if(conn!=null)
{
try
{
conn.close();
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
}
}