JDBC编程详细总结

一、JDBC编程

JDBC编程有标准步骤(八股文)

  • 注册驱动

    • 将sql语句的运行环境加载到JVM

  • 连接数据库

  • 获得执行SQL的对象

  • 执行SQL语句,获得结果

  • 关流

1、 注册驱动

Class.forName("com.mysql.jdbc.Driver");//5.7版本 加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");//5.8版本 加载驱动

2、 连接数据库

  • 通过 DriverManager.getConnection(url,user,password) 获取数据库连接对象

    • URL:jdbc:mysql://localhost:3306/database

      • ?useUnicode=true&characterEncoding=utf8 // 解决数据编码格式乱码

      • &useSSL=false // 解决执行时控制台红色警告

      • &serverTimezone=UTC // mysql8版本需要加时区

    • username:root

    • password:123456

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名字?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC   ", "数据库用户名","数据库密码");
  • URL(Uniform Resource Locator) 统一资源定位符:由协议、IP、端口、SID(程序实例名称)组成

3、 获取发送 SQL 的对象

通过 Connection 对象获得 Statement 对象,用于对数据库进行通用访问。

Statement statement = conn.createStatement();

4、 执行SQL 语句

执行 SQL 语句并接收执行结果。

String sql ="INSERT INTO t_jobs(JOB_ID,JOB_TITLE,MIN_SALARY,MAX_SALARY) VALUES('JAVA_Le','JAVA_Lecturer',4000,10000);";
​
int result = statement.executeUpdate(sql);//执行SQL语句并接收结果

5、 处理结果

接受处理操作结果。

if(result > 0 ){
    System.out.println("Success");
}

6、 释放资源

遵循先开后关原则,释放所使用到的资源对象。

statement.close();
conn.close();

7、 案例

准备数据库表,进行CRUD.

create table tb_user(
 id int(11) primary key auto_increment comment '用户编号',
 username varchar(10) comment '用户名',
 password varchar(10) comment '密码',
 phone varchar(11) comment '手机号',
 create_time date comment '注册时间',
 money double(10,2) comment '账户余额',
 sex int(1) comment '性别 1男2女'
);

需求: 使用JDBC完成对tb_user表插入数据

public class Demo2 {
​
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        // 1 加载驱动
        Class.forName("com.mysql.jdbc.Driver");
​
        // 2 获得连接
        // 通过驱动管理器获得连接
        String url = "jdbc:mysql://localhost:3306/java2401?useUnicode=true&characterEncoding=utf8&useSSL=false";
        // 协议://ip:端口/数据库?参数=值&参数=值
        // http://www.baidu.com:80/s?ie=UTF-8&wd=java
        String username = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, username, password);
​
        // 3 获得执行语句对象
        // 通过连接对象创建语句对象
        Statement statement = connection.createStatement( );
​
        // 4 执行sql获得结果
        // 通过语句对象执行sql,获得结果
        // 增删改都是更新,它们执行的结果都是受影响的行数
        int i = statement.executeUpdate("insert into tb_user values (3,'ww','123','120','2001-01-01',2000.0,2)");
        if (i > 0) {
            System.out.println("插入成功!" );
        }
​
        // 5 关闭连接
        statement.close();
        connection.close();
    }
​
}

二、完成增删改

1、 插入

参考入门案例

2、 更新

任何的JDBC都是那5个步骤.

public class Demo2_update {
​
    public static void main(String[] args) throws Exception {
​
        // 1 加载驱动
        Class.forName("com.mysql.jdbc.Driver");
​
        // 2 通过驱动管理对象获得连接对象
        String url = "jdbc:mysql://localhost:3306/java2311?useSSL=false";
        String username = "root";
        String password = "123456";
        Connection conn = DriverManager.getConnection(url, username, password);
​
        // 3 通过连接对象创建执行语句对象
        Statement statement = conn.createStatement( );
​
        // 4 通过执行语句对象执行sql,获得结果
        String sql = "update tb_user set username = '小孟', phone = '666666' where id = 3";
        int num = statement.executeUpdate(sql);
​
        if (num > 0) {
            System.out.println("更新成功!" );
        }
        // 5 将对象的流关闭
        statement.close();
        conn.close();
    }
}

3、 删除

public class Demo3_delete {
​
    public static void main(String[] args) {
        Statement statement = null;
        Connection conn = null;
        try {
            // 1 加载驱动
            Class.forName("com.mysql.jdbc.Driver");
​
            // 2 获得连接
            String url = "jdbc:mysql://localhost:3306/java2311?useSSL=false";
            String username = "root";
            String password = "123456";
            conn = DriverManager.getConnection(url, username, password);
​
            // 3 获得语句对象
            statement = conn.createStatement( );
​
            // 4 执行sql
            int num = statement.executeUpdate("delete from tb_user where id = 3");
​
            if (num > 0) {
                System.out.println("删除成功" );
            }
        }catch (Exception e) {
            // 如果有异常,要打印出来,因为要根据异常解决问题
            e.printStackTrace();
        } finally {
            try {
                // 5 关闭连接
                statement.close( );
                conn.close( );
            }catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

三、查询结果集ResultSet【重要】

查询返回的是一种虚拟表,Java的JDBC中是使用结果集(ResultSet)来封装这个虚拟表,结果集就是一个集合,内部就存储了列名和每行数据,那么学习查询的重点是

  • 从结果集取值

public class Demo4_select {
    public static void main(String[] args) throws Exception{
​
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java2311?useSSL=false", "root", "123456");
        Statement statement = conn.createStatement( );
        /**
         * 执行查询方法 executeQuery()
         * 返回值是 ResultSet 结果集,其中就包含查询返回的所有数据(一张虚拟表)
         * ResultSet结果集中包含列和行数据,其中有个光标指向表头
         * next() 方法会向下移动一行,返回boolean,为true即有下一行数据,false该行没数据
         * 当指向该行后,有方法可以获取该行列值
         * getXxx()   ps:xxx是各种数据类型
         * getXxx(String columnLabel) 通过列名取值,如果有别名要使用别名
         */
        String sql = "select birthday,money,username,password,id,sex,age from tb_user";
        ResultSet rs = statement.executeQuery(sql);
        while (rs.next()){
            int id = rs.getInt("id");
            String username = rs.getString("username");
            String password = rs.getString("password");
            String sex = rs.getString("sex");
            int age = rs.getInt("age");
            Date birthday = rs.getDate("birthday");
            double money = rs.getDouble("money");
            System.out.println(id+"-"+username+"-"+password+"-"+sex+"-"+age+"-"+birthday+"-"+money);
        }
        rs.close();
        statement.close();
        conn.close();
    }
}

image-20221121164359945

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值