JDBC
本质:是官方定义的一套操作所有关系型数据库的规则,即接口,各个数据库厂商去实现这套接口,我们可以使用这套接口编程,真正执行的代码是驱动jar包中的实现类;
快速入门
- 导入jar包
- 实现案例
public static void main(String[] args){
Connection connection = null;
Statement statement = null;
//注册驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
//获取数据库连接对象
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
//创建sql
String sql = "insert into t_student values (null,'张三')";
//获取执行sql的对象
statement = connection.createStatement();
//执行sql
int i = statement.executeUpdate(sql);
if (i > 0){
System.out.println("运行成功");
}else {
System.out.println("运行失败");
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
//释放资源
//避免空指针
if (statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
JDBC各个对象
DriverManager 驱动管理对象
- 注册驱动
- 获取数据库链接
Connection 数据库连接对象
- 获取执行的sql对象
- 管理事务
Statement 执行sql对象
- 执行sql
注意 : 真实开发会使用preparedStatement对象;
防止sql注入,效率更高;
JDBCUtils
src下新建jdbc.properties
url=jdbc:mysql://localhost/test
user=root
password=root
driver=com.mysql.jdbc.Driver
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String URL;
private static String USER;
private static String PASSWORD;
static {
try {
//创建properties对象
Properties properties = new Properties();
//获取scr路径下的配置文件
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
URL resources = classLoader.getResource("jdbc.properties");
String path = resources.getPath();
//加载配置文件
properties.load(new FileReader(path));
//获得数据
URL = properties.getProperty("url");
USER = properties.getProperty("user");
PASSWORD = properties.getProperty("password");
Class.forName(properties.getProperty("driver"));
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection connection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
/**
* 释放资源
* @param st
* @param conn
*/
public static void close(Statement st, Connection conn){
if(st != null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 释放资源
* @param rs
* @param st
* @param conn
*/
public static void close(ResultSet rs, Statement st, Connection conn){
if (rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(st != null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}