Jdbc 学习笔记

1 jdbc示例

使用jdbc框架,更新数据库中的数据

public static void main(String[] args) throws SQLException, ClassNotFoundException {
        String url = "jdbc:mysql://127.0.0.1:3306/db1";
        String userName = "root";
        String pwd = "1234";

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

        //2 获取链接
        Connection connection;
        connection = DriverManager.getConnection(url, userName, pwd);

        //3 定义sql
        String sql = "update account set money = 2000 where id = 1";

        //4 获取执行sql的对象 Statement
        Statement statement = connection.createStatement();

        //5 执行sql
        int count = statement.executeUpdate(sql);

        //6 输出结果
        System.out.println(count);

        //7 释放资源
        statement.close();
        connection.close();
    }

}

执行结果输出 1

2 jdbc事务使用示例

使用jdbc框架,来实现MySql中事务的操作

public static void main(String[] args) throws Exception {
        //1 注册驱动
        Class.forName("com.mysql.jdbc.Driver");

        //2 获取连接
        String url = "jdbc:mysql:///db1?useSSL = false";
        String useName = "root";
        String passWord = "1234";

        Connection connection = DriverManager.getConnection(url, useName, passWord);

        //3 定义sql
        String sql1 = "update account set money = 3000 where id = 1";
        String sql2 = "update account set money = 3000 where id = 2";

        //4 获取执行sql对象Statement
        Statement statement = connection.createStatement();

        try {
            connection.setAutoCommit(false);
            //5 执行sql
            int count1 = statement.executeUpdate(sql1);//受影响的行数

            System.out.println(count1);

//            int i = 3 / 0;//手动加错误
            int count2 = statement.executeUpdate(sql2);
            System.out.println(count2);

            /* ==============  提交事务  ===============*/
            connection.commit();
        } catch (Exception e) {
            /* ===================== 回滚事务 =======================*/
            connection.rollback();
            e.printStackTrace();
        }


        //6 释放资源
        statement.close();
        connection.close();
    }

以上代码可以正常更新数据库,如果把注释掉的手动错误不注释掉的话,sql1的语句将会被回滚。

3 jdbc执行DQL

使用jdbc来查询数据库中的内容

public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://127.0.0.1:3306/db1";
        String userName = "root";
        String pwd = "1234";

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

        //2 获取链接
        Connection connection;
        connection = DriverManager.getConnection(url, userName, pwd);

        //3 定义sql
        String sql = "select * from account";

        //4 获取执行sql的对象 Statement
        Statement statement = connection.createStatement();

        //5 执行sql
        ResultSet resultSet = statement.executeQuery(sql);

        //6 输出结果
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            double money = resultSet.getDouble("money");

            System.out.println("id = " + id + ", name = " + name + ", money = " + money);
        }

        //7 释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }

输出结果

id = 1, name = 张三, money = 3000.0
id = 2, name = 李四, money = 3000.0

4 sql注入

4.1 模拟注入问题
public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://127.0.0.1:3306/db1";
        String userName = "root";
        String pwd = "1234";
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection(url, userName, pwd);
        String name = "zhsan";
        String password = "' or '1' = '1";
        String sql = "select * from tb_user where username = '"+name + "' and password = '" + password + "'";
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);

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

        resultSet.close();
        statement.close();
        connection.close();
    }

以上代码执行后,不管name和password输入什么值,都会提示登录成功,因为后面的or ‘1’ = ‘1’ 条件成立

4.2 使用PreparedStatement改进注入问题
public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://127.0.0.1:3306/db1";
        String userName = "root";
        String pwd = "1234";
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection(url, userName, pwd);
        String name = "zhsan";
        String password = "' or '1' = '1";
        String sql = "select * from tb_user where username = ? and password = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setString(1, name);
        preparedStatement.setString(2, password);

        ResultSet resultSet = preparedStatement.executeQuery();

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

        resultSet.close();
        preparedStatement.close();
        connection.close();
    }

此时将会输出登录失败,改成正确的用户名和密码后,会提示登录成功

5 数据库连接池

使用数据库连接池来避免频繁的创建和销毁连接,提升系统响应速度。
使用Druid数据库连接池框架

public static void main(String[] args) throws Exception {
        Properties properties = new Properties();
        properties.load(new FileInputStream("Jdbc-Demo/src/druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }

6 jdbc练习

创建表,添加假数据

-- 创建表tb_brand
create table tb_brand(
    id int primary key auto_increment,
    brand_name varchar(20),
    company_name varchar(20),
    ordered int,
    description varchar(100),
    status int
);

-- 添加数据
insert into tb_brand (brand_name, company_name, ordered, description, status)
values('三只松鼠', '三鼠公司', 5, '好吃不贵', '0'),
('华为', '华为数科', 120, '提供高端科技', '1'),
('三只松鼠', '三鼠公司', 50, '美好的事即将发生', '1');
6.1 添加数据
public static void testAdd() throws Exception {
        String brandName = "比亚迪";
        String companyName = "比亚迪车业";
        int ordered = 300;
        String description = "都是电车干就完了";
        int status = 1;

        Properties properties = new Properties();
        properties.load(new FileInputStream("Jdbc-Demo/src/druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        Connection connection = dataSource.getConnection();
        String sql = "insert into tb_brand(brand_name, company_name, ordered, description, status) values(?, ?, ?, ?, ?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setString(1, brandName);
        preparedStatement.setString(2, companyName);
        preparedStatement.setInt(3, ordered);
        preparedStatement.setString(4, description);
        preparedStatement.setInt(5, status);

        int count = preparedStatement.executeUpdate();
        System.out.println("count = " + count);

        preparedStatement.close();
        connection.close();
    }
6.2 查询数据
public static void testSelectAll() throws Exception {
        Properties properties = new Properties();
        properties.load(new FileInputStream("Jdbc-Demo/src/druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        Connection connection = dataSource.getConnection();
        String sql = "select * from tb_brand;";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        Brand brand = null;
        List<Brand> brandList = new ArrayList<>();
        while(resultSet.next()) {
            brand = new Brand();
            brand.setId(resultSet.getInt("id"));
            brand.setBrandName(resultSet.getString("brand_name"));
            brand.setCompanyName(resultSet.getString("company_name"));
            brand.setOrdered(resultSet.getInt("ordered"));
            brand.setDescription(resultSet.getString("description"));
            brand.setStatus(resultSet.getInt("status"));
            brandList.add(brand);
        }

        System.out.println(brandList);
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
6.3 修改数据
public static void testUpdate() throws Exception {
        String brandName = "比亚迪";
        String companyName = "比亚迪车业";
        int ordered = 30;
        String description = "四个车轱辘的车企";
        int status = 1;
        int id = 4;

        Properties properties = new Properties();
        properties.load(new FileInputStream("Jdbc-Demo/src/druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        Connection connection = dataSource.getConnection();
        String sql = "update tb_brand\n" +
                "set brand_name = ?,\n" +
                "company_name = ?,\n" +
                "ordered = ?,\n" +
                "description = ?,\n" +
                "status = ?\n" +
                "where id = ?";

        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setString(1, brandName);
        preparedStatement.setString(2, companyName);
        preparedStatement.setInt(3, ordered);
        preparedStatement.setString(4, description);
        preparedStatement.setInt(5, status);
        preparedStatement.setInt(6, id);

        int count = preparedStatement.executeUpdate();
        System.out.println("count = " + count);

        preparedStatement.close();
        connection.close();
    }
6.4 删除数据
public static void testDelete() throws Exception {
        int id = 4;

        Properties properties = new Properties();
        properties.load(new FileInputStream("Jdbc-Demo/src/druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        Connection connection = dataSource.getConnection();
        String sql = "delete from tb_brand where id = ?";

        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setInt(1, id);

        int count = preparedStatement.executeUpdate();
        System.out.println("count = " + count);

        preparedStatement.close();
        connection.close();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一、概述: JDBC从物理结构上说就是Java语言访问数据库的一套接口集合。从本质上来说就是调用者(程序员)和实现者(数据库厂商)之间的协议。JDBC的实现由数据库厂商以驱动程序的形式提供。JDBC API 使得开发人员可以使用纯Java的方式来连接数据库,并进行操作。 ODBC:基于C语言的数据库访问接口。 JDBC也就是Java版的ODBC。 JDBC的特性:高度的一致性、简单性(常用的接口只有4、5个)。 1.在JDBC中包括了两个包:java.sql和javax.sql。 ① java.sql 基本功能。这个包中的类和接口主要针对基本的数据库编程服务,如生成连接、执行语句以及准备语句和运行批处理查询等。同时也有一些高级的处理,比如批处理更新、事务隔离和可滚动结果集等。 ② javax.sql 扩展功能。它主要为数据库方面的高级操作提供了接口和类。如为连接管理、分布式事务和旧有的连接提供了更好的抽象,它引入了容器管理的连接池、分布式事务和行集等。 注:除了标出的Class,其它均为接口。 API 说明 java.sql.Connection 与特定数据库的连接(会话)。能够通过getMetaData方法获得数据库提供的信息、所支持的SQL语法、存储过程和此连接的功能等信息。代表了数据库。 java.sql.Driver 每个驱动程序类必需实现的接口,同时,每个数据库驱动程序都应该提供一个实现Driver接口的类。 java.sql.DriverManager (Class) 管理一组JDBC驱动程序的基本服务。作为初始化的一部分,此接口会尝试加载在”jdbc.drivers”系统属性中引用的驱动程序。只是一个辅助类,是工具。 java.sql.Statement 用于执行静态SQL语句并返回其生成结果的对象。 java.sql.PreparedStatement 继承Statement接口,表示预编译的SQL语句的对象,SQL语句被预编译并且存储在PreparedStatement对象中。然后可以使用此对象高效地多次执行该语句。 java.sql.CallableStatement 用来访问数据库中的存储过程。它提供了一些方法来指定语句所使用的输入/输出参数。 java.sql.ResultSet 指的是查询返回的数据库结果集。 java.sql.ResultSetMetaData 可用于获取关于ResultSet对象中列的类型和属性信息的对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值