jdbc知识点总结
1、jdbc是什么?
jdbc是用于在Java语言编程中与数据库连接的API。用来将程序连接到数据库,并能通过执行sql语句对数据库进行增删改查操作。
2、使用前准备
mysql数据库驱动jar包下载:https://dev.mysql.com/downloads/connector/j/,下载完成后复制粘贴到项目的lib文件目录中,然后右击add as library,jar包添加完成。
3、使用步骤
- 1、加载驱动
- 2、创建连接
- 3、写sql语句
- 4、得到statement对象
- 5、执行sql得到结果集
- 6、处理结果集
- 7、关闭资源
4、示例代码
一般将与数据库的连接和释放的代码写在util包的Java类中
package com.wuli.util;
import java.sql.*;
public class DBUtil {
public static Connection getConnection(){
//加载驱动、创建连接
try {
//1加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2创建连接
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/user_db?useSSL=true&characterEncoding=utf-8&user=root&password=zxcvbnm.");
return connection;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void shutDown(ResultSet resultSet, PreparedStatement 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();
}