- JDBC API提供各种操作访问接口:
Connection、Statement、PreparedStatement、ResultSet - JDBC DriverManager:管理不同的数据库驱动
- 各种数据库驱动:相应的数据库厂商提供的,连接\字节操作数据库
JDBC API主要功能:
三件事,具体是通过以下类/接口实现
DriverManager:管理数据库驱动
Connection:连接数据库
Statement(Preparedstatement):增删改查
CallableStatement:调用数据库中的 存储过程/存储函数
ResultSet:返回的结果集
连接数据库(这里以mysql数据库为例)的具体操作:
数据库中的数据:
① 导入加载具体的驱动类,这里是MySql数据库的驱动类
导入mysql的jar包
mysql-connector-java-8.0.15
提取码: 6666
Class.forName("com.mysql.jdbc.Driver");
②与数据库建立连接
Connection connection=DriverManager.getConnection(URL, USER, PASSWORD);
③(1)发送SQL执行,增删改
Statement statement=connection.createStatement();
String sql="insert into 表名 values('4','LiSi','000')";
int count=statement.executeUpdate(sql);
③(2)发送SQL执行,查
String sql2="select * from t_account";
ResultSet executeQuery = statement.executeQuery(sql2);
④关闭连接
if (statement!=null)
statement.close();
if (connection!=null)
connection.close();
完整代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCDemo {
private final String URL = "jdbc:mysql://localhost:3306/book?serverTimezone=GMT&useSSL=false";
private final String USER = "root";
private final String PASSWORD = "123456";
public void connection() {
Connection connection = null;
Statement statement = null;
try {
// 加载具体的驱动类,这里是MySql数据库的驱动类
Class.forName("com.mysql.jdbc.Driver");
// 与数据库建立连接
connection = DriverManager.getConnection(URL, USER, PASSWORD);
// 发送SQL执行
statement = connection.createStatement();
String sql1 = "update t_account set username='hello world' where id='4'";
int count = statement.executeUpdate(sql1);
String sql2 = "select * from t_account";
ResultSet executeQuery = statement.executeQuery(sql2);
if (count > 0) {
System.out.println("修改成功");
}
while (executeQuery.next()) {
String string1 = executeQuery.getString(1);
String string2 = executeQuery.getString(2);
String string3 = executeQuery.getString(3);
System.out.println(string1 + "--" + string2 + "--" + string3);
}
} catch (ClassNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
try {
if (statement != null)
statement.close();
if (connection != null)
connection.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JDBCDemo demo = new JDBCDemo();
demo.connection();
}
}
运行结果:
数据库中的数据: