JDBC:Java database Connectivity
JDBC是java程序连接各种数据库的组件
Mybatis就是基于JDBC的封装,是独立于数据库的管理系统,通用的SQL数据库存取和操作的公共接口
定义了一套标准,为访问 不同数据库提供了统一的途径
JDBC接口包含两部分
JDBC API
供开发者调用的类,主要在java.sql和javax.sql包中
DriverManager:管理不同的驱动
JDBC驱动:复制连接不同的数据库
JDBC的原理:
加载数据库驱动,java程序和Mysql的桥梁
获取connection连接,一次连接
创建Statement,由Connection生成,执行sql语句
ResultSet保持Statement执行后产生的结果
建立一次连接:
public static void main(String[] args) throws SQLException {
// 在URL中添加时区参数 serverTimezone=Asia/Shanghai
String url = "jdbc:mysql://localhost:3306/mytest1?serverTimezone=Asia/Shanghai&useSSL=false";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
加载驱动就是将 JDBC 所需要的驱动类加载到 JVM 中才能运行,通过类加载器进行加载,通过反射机制将该类加载进来
Class.forName(类名) 反射机制,获取运行时类,什么是运行时类?
Java 程序是由类组成的,运行时,会将 Java 所有的类添加到 JVM 内存中,并且每个类只有一份,保持在 JVM 内存中的类叫运行时类,JVM 根据运行时类创建不同的对象,Class.forName(类名) 用来加载运行时类的,将驱动程序添加到 JVM 内存中,程序才能访问。
每个类的作用:
DriveManager:驱动管理类,创建Connection,通过用户名,密码,URL进行校验,校验成功创建一个Connection对象
Connection:表示java程序和Mysql之间的一次连接
Statement:表示sql的执行者,复制执行SQL语句
增删改操作 excute():
public static void main(String[] args) throws SQLException {
// 在URL中添加时区参数 serverTimezone=Asia/Shanghai
String url = "jdbc:mysql://localhost:3306/mytest1?serverTimezone=Asia/Shanghai&useSSL=false";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
System.out.println("连接成功");
// 定义sql
// 增加
String insertSql="insert into users(name,gender,score) values('小明','男',90)";
// 删除
String deleteSql="delete from users where name ='小明'";
// 修改
String updateSql="update users set name='述雾' where name = 'c'";
// 执行sql
PreparedStatement preparedStatement = connection.prepareStatement(insertSql);
boolean execute = preparedStatement.execute();
System.out.println(execute);
preparedStatement.close();
preparedStatement = connection.prepareStatement(deleteSql);
preparedStatement.execute();
preparedStatement = connection.prepareStatement(updateSql);
preparedStatement.execute();
connection.close();
preparedStatement.close();
}
excute():负责执行增 删 改方法
返回的结果是return rs != null && rs.hasRows();,判断是否为查询语句,rs != null表示是否有该对象,rs.hasRows()表示是否有值
executeQuery:负责执行查询方法,返回值 ResultSet,集合,查询肯定要返回查到的数据
返回的结果是一个ResultSet
通过ResultSet的next方法可以取出每一行的值
ResultSet resultSet = preparedStatement.executeQuery();
System.out.println(resultSet.getMetaData().getColumnCount());
while (resultSet.next()){
// 方法一
// String name = resultSet.getString("name");
// String gender = resultSet.getString("gender");
// double score = resultSet.getDouble("score");
// 方法2
String name = resultSet.getString(1);
String gender = resultSet.getString(2);
double score = resultSet.getDouble(3);
System.out.println(name+" "+gender+" "+score);
}
这样每次操作都需要创建Connection,然后创建Statement对象然后执行吗?这样不显得太麻烦了吗
我们可以创建一个工具类来获取Connection连接,一个创建多次使用嘛,然后还可以封装一些方法来更新数据库的字段值
比如创建一个JDBCUtil工具类
在创建的时候初始化该类,初始化Connection对象,然后在insertUsers写一个方法插入到users表中
public class JDBCUtil {
public static final String URL = "jdbc:mysql://localhost:3306/mytest1?useSSL=true&serverTimezone=GMT%2B8";
public static final String USER = "root";
public static final String PASSWORD = "root";
public static final String DRIVER = "com.mysql.cj.jdbc.Driver";
private Connection connection = null;
// 获取连接
public void initConnection(){
try {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL, USER, PASSWORD);
System.out.println("连接成功");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public JDBCUtil(){
initConnection();
}
// 关闭连接
public void closeConnection(){
if (connection != null){
try {
connection.close();
System.out.println("关闭连接");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
// 插入到users表字段
public void insertUsers(String name,String gender,Integer score){
String sql = "insert into users(name,gender,score) values('"+name+"','"+gender+"',"+score+")";
System.out.println(sql);
PreparedStatement preparedStatement = null;
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.execute();
System.out.println("插入成功");
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
try {
preparedStatement.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
测试函数
public class Test {
public static void main(String[] args) throws SQLException {
JDBCUtil jdbcUtil = new JDBCUtil();
jdbcUtil.insertUsers("张三","男",100);
}
}
成功插入
但是有个问题就是这样写sql赋值的时候显得太麻烦了,我们可以用占位符来解决
String sql = "insert into users(name,gender,score) values('"+name+"','"+gender+"',"+score+")";
String sql = "insert into users(name,gender,score) values(?,?,?)";
System.out.println(sql);
PreparedStatement preparedStatement = null;
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,name);
preparedStatement.setString(2,gender);
preparedStatement.setInt(3,score);
preparedStatement.execute();
System.out.println("插入成功");
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
try {
preparedStatement.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
用preparedStatement.setString(占位符的位置,赋值的参数);
根据参数的类型可以选择setString(),setInt,setDouble…来设置,这样就好写多了
下一篇我们来讲解更加高级通用的方法