JDBC基础详解

JDBC基础

一、基本模板

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public static void main(String[] args) throws Exception {
        Statement stmt = null;
        Connection conn =null;
        try {
//        注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
//        获取数据库对象
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8", "root", "0211");
//        定义sql语句
            String sql = "insert into test value (null,'wu');";
//        获取执行对象
            stmt = conn.createStatement();
//        执行sql
            int count = stmt.executeUpdate(sql);
//        处理结果
            if (count>0){
                System.out.println("success");
            }else {
                System.out.println("faild");
            }

        } catch(ClassNotFoundException e){
            e.printStackTrace();
        }catch (SQLException E){
            E.printStackTrace();
        }finally {
            //        释放资源
            if(stmt != null){
                try{
                    stmt.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
            if(conn != null){  //防止空指针异常
                try{
                    conn.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
        }

    }
  1. ClassNotFoundException 是为了防止 注册驱动异常而抛出的
  2. SQLException 是为了防止 链接数据库或者书写sql语句异常 而抛出的

二、对象详解

1、DriverManager:驱动管理对象

  • 注册驱动、获取数据库链接

2、Connection:数据库链接对象

  • 获取执行sql的对象:
    • Statement createStatement()
    • PreparedStatement PreparedStatement(String sql)
  • 管理事务
    • 开启事务:setAutoCommit(boolean autoCommit),设置参数为false即为开启事务
    • 提交事务:commit()
    • 回滚事务:rollback()

3、Statement

  • 执行sql
    • boolean excute(String sql):可以执行任意sql 了解即可
    • int rxcuteUpdate(String sql):执行DML(update,insert,delete)、DDL(create,drop,alter)
      • 返回值是受影响函数
    • ResultSet excuteQuery(String sql) :执行DQL(select)
      • 返回结果集对象

4、ResultSet

  • next():游标向下移动一行
  • getXxx(参数):获取数据
    • Xxx代表数据类型 int 、String等等
    • 参数:
      • int:代表列的编号,从1开始 :getString(1)
      • String:代表列名 :getDouble(“**”)

三、利用JDBC对数据增删查

1、创建简单的数据库:

create table test(

id int primary key,

name varchar(20)

);
--设置主键自增
alter table test modify id int auto_increment; 

2、对数据进行增删查:

    public static void main(String[] args) throws Exception {
        Statement stmt = null;
        Connection conn =null;
        try {
//        注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
//        获取数据库对象
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8", "root", "0211");
//        定义sql语句
            String sql = "insert into test value (null,'wu');";
//        获取执行对象
            stmt = conn.createStatement();
//        执行sql
            int count = stmt.executeUpdate(sql);
//        处理结果
            if (count>0){
                System.out.println("success");
            }else {
                System.out.println("faild");
            }

        } catch(ClassNotFoundException e){
            e.printStackTrace();
        }catch (SQLException E){
            E.printStackTrace();
        }finally {
            //        释放资源
            if(stmt != null){
                try{
                    stmt.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
            if(conn != null){  //防止空指针异常
                try{
                    conn.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
        }

    }

增删查等操作用把定义sql语句中的内容改为目标sql语句

3、对数据进行查询:

    public static void main(String[] args) throws Exception {
        Statement stmt = null;
        Connection conn =null;
        ResultSet count = null;
        try {
//        注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
//        获取数据库对象
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8", "root", "0211");
//        定义sql语句
            String sql = "select *from test;";
//        获取执行对象
            stmt = conn.createStatement();
//        执行sql
            count = stmt.executeQuery(sql);
//        处理结果
//           向下移动一行
//                获取数据
            while(count.next()) {
                ;
                int id = count.getInt(1);
                String name = count.getString("name");
                System.out.println(id + name);
            }
        } catch(ClassNotFoundException e){
            e.printStackTrace();
        }catch (SQLException E){
            E.printStackTrace();
        }finally {
            //        释放资源
            if(count != null){
                try{
                    count.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
            if(stmt != null){
                try{
                    stmt.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
            if(conn != null){  //防止空指针异常
                try{
                    conn.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
        }

    }
  • 与增删查操作不同有以下几点:

    //1、执行sql这一步需要使用 ResultSetQuery(),该方法返回的是一个数据集 ResultSet对象
    //2、使用while语句对表里所有数据遍历,并打印所有数据
    //3、获取单条数据则讲执行sql部分改为:
        count.next();
        int id = count.getInt(1);
        String name = count.getString("name");
        System.out.println(id +"----"+ name);        
    
  • PS:

    • count.next()返回的是一个 int 型的值,指的是数据表中的数据条数
    • 使用mysql8.0.17 jdk1.8
    • 驱动下载链接:https://mvnrepository.com/artifact/mysql/mysql-connector-java
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值