JDBCUtils工具类编写

什么是JDBC:

JDBC全称: java database connection。
Jdbc主要用于java代码连接数据库,java代码就可以发送sql语句给数据库服务器,操作数据库中数据。

获取连接步骤:

导入数据库的驱动包(mysql-connector-java-5.1.37-bin.jar)。
在当前的模块上新建一个文件夹(lib),然后把jar拷贝进去。
让当前的模块关联该jar包。
JDBCUtils工具类编写:

为什么需要自定义工具类:

在做增、删除、修改、查询都需要获取Connection连接,使用完毕之后我们都需要关闭连接,这些工作是不断的重复在做的事情,所以我们可以把这些工作定义成一个工具类的方法,减少我们重复代码的编写。
步骤:

1.固定字符串=常量(大写)
2.静态代码块
3.连接方法getConnection()
4.关闭连接close(ResultSet rs,Statemment st,Connection connection)
5.重写close(Statemment st,Connection connection)(声明:不重写,也可以调用close()方法时将4中的rs设为NULL);
import java.sql.*;

public class JdbcUtils {
//1.固定字符串=常量(大写)
public static final String DRIVERCLASS = "com.mysql.jdbc.Driver";
//url = 协议://ip地址:端口号/数据库名称
public static final String URL = "jdbc:mysql://localhost:3306/aaa";
public static final String USER = "root";
public static final String PASSWORD = "root";
//2.静态代码块(只执行一次)
static {
try {
Class.forName(DRIVERCLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 3.连接方法getConnection()
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//4.关闭连接close(ResultSet rs,Statemment st,Connection connection)
public static void close(ResultSet resultset, Statement statement, Connection connection) {
if (resultset != null) {
try {
resultset.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 5.重写close(Statemment st,Connection connection)(声明:不重写,也可以将rs设为NULL);
public static void close(Statement statement, Connection connection) {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

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
JDBC常用的方法:

Statement createStatement() 创建一个 Statement 对象来将 SQL 语句发送到数据库
boolean execute(String sql) 此方法可以执行任意sql语句。返回boolean值,表示是否返回ResultSet结果集。仅当执行select语句,且有返回结果时返回true,
其它语句都返回false;
int executeUpdate(String sql) 根据执行的DML(INSERT、UPDATE、DELETE)语句,返回受影响的行数
ResultSet executeQuery(String sql) 根据查询语句返回结果集,只能执行SELECT语句
查询:
一个sql语句是查询的时候会返回一个ResultSet对象,ResultSet对象代表了本次的查询结果集。
ResultSet常用的方法:

---------------------

posted @ 2019-07-24 01:29  水至清明  阅读(532)  评论(0编辑  收藏  举报