JDBC——API详解

风陵南·2022-09-16 00:18·149 次阅读

JDBC——API详解

DiverManager

  DriverManager(驱动管理类)作用:

    1. 注册驱动

 

      MySQL 5之后的版本 不再需要手动写这行注册驱动的代码了(可以省略) 

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

 

 

    2. 获取数据库连接

        // 2.获取连接  如果连接的是本机数据库 可胜率省略IP地址和端口号 jdbc:mysql:///数据库名称?参数键值对
        String url = "jdbc:mysql://127.0.0.1:3306/db_0915?useSSL=false";
        String username = "root";
        String password = "1234";
        Connection conn = DriverManager.getConnection(url,username,password);

 

      参数:

        1. url :连接路径

          语法:jdbc:mysql://ip地址:端口号/数据库名称?参数键值对1&参数键值对2...

          示例:jdbc:mysql://127.0.0.1:3306/db_0915

          细节:

            如果连接的是本机的mysql服务器,并且mysql 服务器默认端口是3306,则可以简写为:jdbc:mysql:///数据库名称?参数键值对

            配置 useSSL = false 参数,禁用安全连接方式,解决警告提示

        2. user:用户名

        3. password:密码

 

 

Connection

  Connection(数据库连接对象)作用:

    1. 获取执行SQL的对象

      普通执行SQL对象

Statement createStatement()

 

       预编译SQL的执行SQL对象:防止SQL注入

PreparedStatement prepareStatement(sql)

 

 

    2. 管理事务

开启事务:setAutoCommit(boolean aotoCommit)   true为自动提交事务,false为手动提交事务 即为开启事务

提交事务:commit()

回滚事务:rollback()

 

    示例:

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

        // 2.获取连接
        String url = "jdbc:mysql://127.0.0.1:3306/db_0915?characterEncoding=utf8&useSSL=true";
        String username = "root";
        String password = "1234";
        Connection conn = DriverManager.getConnection(url,username,password);

        // 3. 定义sql
        String sql1 = "update account set money = 3000 where name = '张三'";
        String sql2 = "update account set money = 3000 where name = '李四'";

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

        // 开启事务
        conn.setAutoCommit(false);

        try {
            // 5.执行SQL
            int count1 = stmt.executeUpdate(sql1);  // 受影响的行数

            // 6. 处理结果
            System.out.println(count1);

            // 5.执行SQL
            int count2 = stmt.executeUpdate(sql2);  // 受影响的行数

            // 6. 处理结果
            System.out.println(count2);

            // 提交事务
            conn.commit();
        } catch (Exception e) {
            // 回滚事务
            conn.rollback();
            throw new RuntimeException(e);
        }



        // 7. 释放资源
        stmt.close();
        conn.close();
复制代码

 

 

Statement

  执行SQL语句

    

int executeUpdate(sql) :执行DML、DDL语句

返回值(1)DML语句影响的行数
         (2)DDL语句执行后可能返回0
ResultSet executeQuery(sql) :执行DQL语句

返回值 :ResultSet 结果集对象

 

 

ResultSet

  ResultSet (结果集对象)作用:

    1. 封装了DQL查询语句的结果

 

ResultSet stmt.executeQuery(sql)  :执行DQL语句,返回ResultSet对象

 

        获取查询结果

boolean next()  :(1)将光标从当前位置向前移动一行
                          (2)判断当前行是否为有效行
    返回值:
        true : 有效行,当前行有数据
        false : 无效行,当前行没有数据
xxx getXxx(参数)  :获取数据
    xxx :数据类型;如:int getInt(参数);String getString(参数)
    参数:
        int :列的编号,从1开始
        String :列的名称

        使用步骤:

          1. 游标向下移动一行,并判断该行是否有数据:next()

          2. 获取数据:getXxx(参数)

    

// 循环判断游标是否最后一行末尾
while(rs.next()){
    // 获取数据
    rs.getXxx(参数);
)

      案例:

     

    Account类

复制代码
public class Account {
    private int id;
    private String name;
    private double money;

    public Account(int id, String name, double money) {
        this.id = id;
        this.name = name;
        this.money = money;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                "}\n";
    }
}
复制代码

    主程序:

复制代码
/**
     * ResultSet 案例
     * 查询account账户表数据,封装为Account对象,并且存储到ArrayList集合中
     */
    public static void main(String[] args) throws Exception {

        // 1.注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        // 2.获取连接
        String url = "jdbc:mysql://127.0.0.1:3306/db_0915?characterEncoding=utf8&useSSL=true";
        String username = "root";
        String password = "1234";
        Connection conn = DriverManager.getConnection(url,username,password);
        // 3. 定义sql
        String sql = "select * from account";
        // 4. 获取Statement对象
        Statement stmt = conn.createStatement();
        // 5. 执行sql
        ResultSet rs = stmt.executeQuery(sql);
        //6. 处理执行结果
        ArrayList<Account> accounts = new ArrayList<>();  // 账户表
        while(rs.next()){
            Account account = new Account(rs.getInt("id"),
                                    rs.getString("name"),rs.getDouble("money"));
            accounts.add(account);
        }
        System.out.println(accounts);
    }
复制代码

 

 

PreparedStatement

  作用:预编译SQL并执行SQL语句

    ①获取 PreparedStatement 对象

//SQL语句中的参数值,使用 ? 占位符替代
String sql = "select * from user where username = ? and password = ?";

// 通过Connection 对象获取,并传入对应的sql语句
PreparedStatement pstmt = conn.prepareStatement(sql);

 

    ②设置参数值

 

PreparedStatement 对象: setXxx(参数1,参数2)   给 ? 赋值
     Xxx:数据类型 ; 如 setInt(参数1, 参数2)
    参数:
        参数1:?的位置编号,从1开始
        参数2:?的值

 

    ③执行SQL

 

1
2
executeUpdate();  / executeQuery();
    不需要再传递sql

 

  

    示例:

复制代码
/**
     * 用户登录  ——PreparedStatement 防SQL注入
     */
    @Test
    public void testUserLogin() throws Exception{
        // 1.注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        // 2.获取连接
        String url = "jdbc:mysql://127.0.0.1:3306/db_0915?characterEncoding=utf8&useSSL=true";
        String username = "root";
        String password = "1234";
        Connection conn = DriverManager.getConnection(url,username,password);
        //  接收用户名和密码
        String name = "zhangsan";
        //String pwd = "' or '1' = '1 ";   ---------登录失败
        String pwd = "123";
        //定义sql  name 和 pwd 用在占位符替代
        String sql = "select * from tb_user where username = ? and password = ?";
        //通过conn获取PreparedStatement对象
        PreparedStatement pstmt = conn.prepareStatement(sql);
        // 设置参数
        pstmt.setString(1,name);
        pstmt.setString(2,pwd);
        //执行sql
        ResultSet rs = pstmt.executeQuery();
        //结果判断
        if(rs.next()){
            System.out.println("登录成功~");
        }else{
            System.out.println("登录失败~");
        }
        // 释放资源
        rs.close();
        pstmt.close();
        conn.close();

    }
复制代码

 

   预编译 需要手动开启

 

    PreparedStatement 预编译功能开启: useServerPrepStmts=true

 

   原理:

 

 

 

 

posted @   风陵南  阅读(149)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示