展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

javaweb开发(十一):JDBC连接MySQL

  • jdbc简介
全称 Java DataBase Connectivity, 是Java语⾔中⽤来规范客户端程序如何来访问数据库的应
⽤程序接⼝
提供了⼀种接⼝基准,可以构建更⾼级的⼯具和接⼝,使数据库开发⼈员能够编写数据库应
⽤程序
应⽤程序代码⼀般不能直接访问数据库,需要通过相应的数据库驱动程序才⾏,通俗来说就是数据库⼚商的JDBC接⼝实现
  • 相关概念
数据库驱动:不同数据库开发商(⽐如oracle mysql等)为了某⼀种开发语⾔能够实现统⼀的数
据库调⽤⽽开发的⼀个程序, 作⽤相当于⼀个翻译⼈员, 将某个语⾔(⽐如java)中对数据库
的调⽤通过这个翻译成各个种类的数据库 ⾃⼰的数据库语⾔
Connection连接:特定数据库的连接(会话),在连接上下⽂中执⾏sql语句并返回结果
Statement 语句: 创建执⾏SQL语句的statement, 有好⼏种实现类,⽤于执⾏对应的sql
ResultSet结果集:SQL查询返回的结果信息
  • 连接步骤
加载JDBC驱动程序
建⽴数据库连接Connection
创建执⾏SQL的语句Statement
处理执⾏结果ResultSet
释放连接资源
  • 构建web项目,配置tomcat,导入依赖

  • 创建数据库表

CREATE TABLE `user` (
 `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
 `phone` varchar(32) DEFAULT NULL,
 `pwd` varchar(128) DEFAULT NULL,
 `sex` int(2) DEFAULT NULL,
 `img` varchar(128) DEFAULT NULL,
 `create_time` datetime DEFAULT NULL,
 `role` int(11) DEFAULT NULL COMMENT '1是普通⽤户,2是管理员',
 `username` varchar(128) DEFAULT NULL,
 `wechat` varchar(128) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

# 添加数据
INSERT INTO `user` (`id`, `phone`, `pwd`, `sex`, `img`, `create_time`, `role`,
`username`,`wechat`)
VALUES
 (1,'123','666',1,'xdclass.net','2021-09-09
00:00:00',1,'jack','xdclass6'),
 (2,'2323432','794666918',1,'wwwww','2020-05-20 04:54:01',1,'⼩滴Anna姐
姐','xdclass-anna'),
 (3,'2323432','xdclass-lw',1,'wwwww','2020-05-20 04:54:42',1,'⼆当家⼩
D','xdclass1'),
 (4,'2323432','3232323',1,'wwwww','2020-05-20 04:55:07',1,'⽼
王','xdclass-lw');

  • 编写测试类
public class JdbcTest {

    public static void main(String [] args) throws Exception{
        //加载JDBC驱动程序
        Class.forName("com.mysql.cj.jdbc.Driver");
        //建立数据库连接Connection
        String username = "root";
        String password = "123456";
        //协议:子协议://ip:端口/数据库名称?参数1=值1&参数2=值2
        String url = "jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        Connection connection = DriverManager.getConnection(url,username,password);
        //创建执行SQL的语句Statement
        Statement statement  = connection.createStatement();
        //处理执行结果ResultSet
        ResultSet resultSet = statement.executeQuery("select * from user");
        while (resultSet.next()){
            System.out.println("用户名称 name="+ resultSet.getString("username") + "  联系方式 wechat="+ resultSet.getString("wechat"));
        }
        //释放连接资源
        statement.close();
        connection.close();
    }

}
  • 控制台打印
用户名称 name=jack  联系方式 wechat=xdclass6
用户名称 name=⼩滴Anna姐
姐  联系方式 wechat=xdclass-anna
用户名称 name=⼆当家⼩
D  联系方式 wechat=xdclass1
用户名称 name=⽼
王  联系方式 wechat=xdclass-lw

Process finished with exit code 0
  • 防止sql注入攻击
    private static  void  testInjectSQL()throws Exception{
        //加载JDBC驱动程序
        Class.forName("com.mysql.cj.jdbc.Driver");
        //建立数据库连接Connection
        String username = "root";
        String password = "123456";
        //协议:子协议://ip:端口/数据库名称?参数1=值1&参数2=值2
        String url = "jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        Connection connection = DriverManager.getConnection(url,username,password);
        // 查询条件
        String name = "jack";
        String pwd = "666";
        //创建执行SQL的语句Statement
        PreparedStatement preparedStatement  = connection.prepareStatement("select * from user where username=? and pwd=?");
        preparedStatement.setString(1,name);
        preparedStatement.setString(2,pwd);
        //处理执行结果ResultSet
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()){
            System.out.println("用户名称 name="+ resultSet.getString("username") + "  联系方式 wechat="+ resultSet.getString("wechat"));
        }
        //释放连接资源
        preparedStatement.close();
        connection.close();
    }
  • 测试结果
用户名称 name=jack  联系方式 wechat=xdclass6

Process finished with exit code 0
  • 添加数据
    private static void testAdd() throws Exception {
        //加载JDBC驱动程序
        Class.forName("com.mysql.cj.jdbc.Driver");
        //建立数据库连接Connection
        String username = "root";
        String password = "123456";
        //协议:子协议://ip:端口/数据库名称?参数1=值1&参数2=值2
        String url = "jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        Connection connection = DriverManager.getConnection(url, username, password);
        PreparedStatement preparedStatement = connection.prepareStatement("insert into  user(username, pwd,sex,role,create_time) values(?,?,?,?,?) ");
        preparedStatement.setString(1,"二当家小D");
        preparedStatement.setString(2,"123456");
        preparedStatement.setInt(3,1);
        preparedStatement.setInt(4,2);
        preparedStatement.setTimestamp(5,new Timestamp(System.currentTimeMillis()));
        //执行
        preparedStatement.execute();
        preparedStatement.close();
        connection.close();
    }
  • 测试结果:添加成功

  • 删除

    private static void testDelete() throws Exception {
        //加载JDBC驱动程序
        Class.forName("com.mysql.cj.jdbc.Driver");
        //建立数据库连接Connection
        String username = "root";
        String password = "123456";
        //协议:子协议://ip:端口/数据库名称?参数1=值1&参数2=值2
        String url = "jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        Connection connection = DriverManager.getConnection(url, username, password);
        PreparedStatement preparedStatement = connection.prepareStatement("delete  from user where  id=?");
        preparedStatement.setInt(1,2);
        //执行
        preparedStatement.execute();
        preparedStatement.close();
        connection.close();
    }
  • 测试结果,删除id为2的数据

  • 事务简介

⼀个最⼩的不可再分的⼯作单元,通常⼀个事务对应⼀个完整的业务
例如银⾏账户转账业务,该业务就是⼀个最⼩的⼯作单元
  • 事务特性
原⼦性(A):事务是最⼩单位,不可再分
⼀致性(C):事务要求所有的DML语句操作的时候,必须保证同时成功或者同时失败
隔离性(I):事务A和事务B之间具有隔离性
持久性(D):是事务的保证,事务终结的标志(内存的数据持久到硬盘⽂件中
  • 事务术语
开启事务:Start Transaction
事务结束:End Transaction
提交事务:Commit Transaction
回滚事务:Rollback Transaction
  • 实践代码
    private static void testTransaction() throws Exception {
        //加载JDBC驱动程序
        Class.forName("com.mysql.cj.jdbc.Driver");
        //建立数据库连接Connection
        String username = "root";
        String password = "123456";
        //协议:子协议://ip:端口/数据库名称?参数1=值1&参数2=值2
        String url = "jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        Connection connection = DriverManager.getConnection(url, username, password);
        try (
                PreparedStatement ps1 = connection.prepareStatement("insert into  user(username, pwd) values(?,?) ");
                PreparedStatement ps2 = connection.prepareStatement("insert into  user(username, pwd) values(?,?) ")) {
            //JDBC中默认事务是自动提交的,false就不会自动提交
            connection.setAutoCommit(false);
            // 要插入的数据
            ps1.setString(1, "1111tranc ps 1二当家小D");
            ps1.setString(2, "123456");
            // 要插入的数据
            ps2.setString(1, "2222tranc ps 2二当家小D");
            ps2.setString(2, "123456");
            // 插入第1条数据
            ps1.execute();
            //模拟异常
            int i = 1/0;
            // 插入第2条数据
            ps2.execute();
        } catch (Exception e) {
            e.printStackTrace();
            //事务回滚
            connection.rollback();
        } finally {
            //事务提交
            connection.commit();
            connection.close();
        }
    }
  • 测试成功,数据库无变化,控制台打印如下
java.lang.ArithmeticException: / by zero
	at com.ychen.web.dao.JdbcTest.testTransaction(JdbcTest.java:151)
	at com.ychen.web.dao.JdbcTest.main(JdbcTest.java:45)

Process finished with exit code 0
posted @ 2022-04-15 13:46  DogLeftover  阅读(27)  评论(0编辑  收藏  举报