首页 > 技术文章 > JAVA-JDBC

DQGonoes 2021-12-17 17:13 原文

JDBC的作用

通过JAVA连接数据库进行操作的软件接口

JDBC的组成

DriverManager :依据数据库的不同,管理JDBC驱动
Connection :负责连接数据库并担任传送数据的任务
Statement :由 Connection 产生、负责执行SQL语句
ResultSet:负责保存Statement执行后所产生的查询结果

准备MYSQL的驱动类JAR包

(1)打开网址https://mvnrepository.com/

(2)搜索mysql

(3)选择“mysql-connector/J”

(4)选择对应数据库版本的JAR包:5.0~ 全使用8.0下载人数最多的包

(5)点击选择的版本号

(6)进入新页面点击“jar”进行下载

(7)将jar包放入idea项目下,在项目路径中建立一个lib包目录,将jar包放入文件夹

(8)在idea中对jar包右键-》add as Library-》ok 就导入了

JDBC代码编写:

(1)注册驱动

//JDBC驱动的注册
        Class.forName("com.mysql.cj.jdbc.Driver");

(2)创建数据库连接

//创建连接
        String url = "jdbc:mysql://127.0.0.1:3306/huawei?characterEncoding=UTF-8&serverTimezone=UTC";
        String userName = "root";
        String pwd = "root123456";
        //获取连接对象
        Connection con = DriverManager.getConnection(url, userName, pwd);

连接的参数:

characterEncoding=UTF-8 //设置服务端字符集
serverTimezone=UTC  //设置服务端的时区
autoReconnect=true  //设置连接断开后自动连接(连接池)

(3)创建查询对象 Statement

//创建查询对象
        Statement statement = con.createStatement();

3.1 进行查询

//查询数据
        //SQL语句
        String sql = "select * from class";

        //执行查询后会返回ResultSet对象
        ResultSet resultSet = statement.executeQuery(sql);

异常:SQL写错:SQLSyntaxErrorException

ResultSet 遍历问题

while(resultSet.next()){//判断是否有下行数据
            //通过对应类型获取字段方法(通过投影顺序下标:从1开始的)
            int anInt = resultSet.getInt(1);

            //通过对应类型获取字段方法(通过投影的名称)
            String string = resultSet.getString("caption");

            System.out.println(anInt+" "+string);

        }

3.2进行增、删、改 executeUpdate(sql)

//执行插入\修改\删除语句 使用executeUpdate,返回受影响的行数
        int i = statement.executeUpdate(sql);

3.3 判断SQL语句是否有结果集返回 execute(sql)

//判断是否有结果集:如果SQL是查询就是true,如果是增删改返回false
        boolean execute = statement.execute(sql2);

(3-1) PreparedStatement查询对象

目的:防止SQL注入

//创建PreparedStatement查询对象
        PreparedStatement ps = con.prepareStatement(sql);//提前把sql交给对象去编译

        //设置占位符的参数值,调用set方法,第一个参数:占位符的下标(从1开始),第二个参数:设置的值
        ps.setString(1,"admin");
        ps.setString(2,"12'or'1'='1");

        System.out.println(ps);
        //进行查询或者增删改
        ResultSet resultSet = ps.executeQuery();

        if(resultSet.next()){
            System.out.println("成功!");
        }else{
            System.out.println("失败!");
        }

(3-2) jdbc也能执行事务

//提前提供sql
        String sql = "update class set caption='456'";

        String sql2 = "update class set caption='789'";

        String sql1_1 = "select * from class";

        Statement statement = con.createStatement();

        statement.execute("BEGIN");

        statement.executeQuery(sql1_1);

        statement.executeUpdate(sql2);

        statement.execute("COMMIT");

(4)关闭流、关闭连接

//关闭jdbc流
        resultSet.close();//结果集
        statement.close();//查询对象
        con.close();//连接对象

异常:

(1)数据库拒绝连接

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
at com.m

原因:

(1)登录的账号没有开通远程登录的权限

update user set host='%' where user='root';
FLUSH PRIVILEGES;

(2)在my.ini配置文件中配置一下选项(【mysqld】)

bind-address = 0.0.0.0

wait_timeout = 249999

(3) MySQL运行的版本与你的MySQL-Connector/j的jar包版本不兼容

++5.0 ~ : 8.0的jar包 (8.0.22)

++6.0~ 8.0: 6.0对应你数据库版本的jar包

(4)切换JDK至1.8版本

(2)数据库时区错误

The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

原因:

数据库服务器时钟和客户端无法同步,所以要在URL后面添加一个时区参数

String url = "jdbc:mysql://127.0.0.1:3306/huawei?characterEncoding=UTF-8&serverTimezone=UTC";

JDBC加上异常处理和事务处理的完整代码

//JDBC驱动的注册
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        //创建连接
        String url = "jdbc:mysql://127.0.0.1:3306/huawei?characterEncoding=UTF-8&serverTimezone=UTC";
        String userName = "root";
        String pwd = "root123456";
        //获取连接对象
        Connection con = null;
        Statement statement = null;
        try {
            con = DriverManager.getConnection(url, userName, pwd);

            //提前提供sql
            String sql = "update class set caption='456'";

            String sql2 = "update class set caption='789'";

            String sql1_1 = "select * from class";

            statement = con.createStatement();

            
            statement.execute("BEGIN");
            
            try {
                statement.executeQuery(sql1_1);
            }catch (SQLException e){
                statement.execute("ROLLBACK ");
            }

            try {
                statement.executeUpdate(sql2);
            }catch (SQLException e){
                statement.execute("ROLLBACK ");
            }

            statement.execute("COMMIT");
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭jdbc流
            try {
                statement.close();
                con.close();//连接对象
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

推荐阅读