zoukankan      html  css  js  c++  java
  • jdbc-基础

    相关概念

    1.什么是JDBC

      JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。

    2.数据库驱动

      我们安装好数据库之后,我们的应用程序也是不能直接使用数据库的,必须要通过相应的数据库驱动程序,通过驱动程序去和数据库打交道。其实也就是数据库厂商的JDBC接口实现,即对Connection等接口的实现类的jar文件。

    常用接口

    1、Driver接口:Driver接口由数据库厂家提供,作为java开发人员,只需要使用Driver接口就可以了。在编程中要连接数据库,必须先装载特定厂商的数据库驱动程序,不同的数据库有不同的装载方法。如:装载MySql驱动:Class.forName("com.mysql.jdbc.Driver");装载Oracle驱动:Class.forName("oracle.jdbc.driver.OracleDriver");

    2、Connection接口:Connection与特定数据库连接,在连接上下文中执行sql语句并返回结果。

    • 连接MySql数据库:Connection conn = DriverManager.getConnection("jdbc:mysql://host:port/database", "user", "password");
    • 连接Oracle数据库:Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@host:port:database", "user", "password");
    • 连接SqlServer数据库:Connection conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://host:port; DatabaseName=database", "user", "password");

    常用方法:

      createStatement():创建向数据库发送sql的statement对象。

      prepareStatement(sql):创建向数据库发送预编译sql的PrepareSatement对象。

      prepareCall(sql):创建执行存储过程的callableStatement对象。

      setAutoCommit(boolean autoCommit):设置事务是否自动提交。

      commit():提交事务。

      rollback():回滚事务。

    3、Statement接口:用于执行静态SQL语句并返回它所生成结果的对象。

    • Statement:由createStatement创建,用于发送简单的SQL语句(不带参数)。
    • PreparedStatement:继承自Statement接口,由preparedStatement创建,用于发送含有一个或多个参数的SQL语句。
    • CallableStatement:继承自PreparedStatement接口,由方法prepareCall创建,用于调用存储过程。

    常用方法:

      execute(String sql):运行语句,返回是否有结果集

      executeQuery(String sql):运行select语句,返回ResultSet结果集。

      executeUpdate(String sql):运行insert/update/delete操作,返回更新的行数。

      addBatch(String sql) :把多条sql语句放到一个批处理中。

      executeBatch():向数据库发送一批sql语句执行。

    4、ResultSet接口:ResultSet提供检索不同类型字段的方法。

    常用方法:

      getString(int index)、getString(String columnName):获得在数据库里是varchar、char等类型的数据对象。

      getFloat(int index)、getFloat(String columnName):获得在数据库里是Float类型的数据对象。

      getDate(int index)、getDate(String columnName):获得在数据库里是Date类型的数据。

      getBoolean(int index)、getBoolean(String columnName):获得在数据库里是Boolean类型的数据。

      getObject(int index)、getObject(String columnName):获取在数据库里任意类型的数据。

    ResultSet还提供了对结果集进行滚动的方法:

      next():移动到下一行

      Previous():移动到前一行

      absolute(int row):移动到指定行

      beforeFirst():移动resultSet的最前面。

      afterLast():移动到resultSet的最后面。

    使用后依次关闭对象及连接:ResultSet → Statement → Connection

    连接数据库

     1 public class GetConnection {
     2 
     3     //连接数据库的URL
     4     private String url = "jdbc:mysql://localhost:3306/ysdrzp";
     5     //用户名
     6     private String user = "root";
     7     //密码
     8     private String password = "root";
     9 
    10     /**
    11      * 第一种方式
    12      * @throws Exception
    13      */
    14     @Test
    15     public void test1() throws Exception{
    16 
    17         // 1、创建驱动程序类对象
    18         Driver driver = new com.mysql.jdbc.Driver();
    19         Properties props = new Properties();
    20         props.setProperty("user", user);
    21         props.setProperty("password", password);
    22         // 2、连接数据库,返回连接对象
    23         Connection conn = driver.connect(url, props);
    24         System.out.println(conn);
    25     }
    26 
    27     /**
    28      * 第二种方式
    29      * @throws Exception
    30      */
    31     @Test
    32     public void test2() throws Exception{
    33 
    34         // 创建驱动程序类对象
    35         Driver driver = new com.mysql.jdbc.Driver();
    36         // 1、注册驱动程序
    37         DriverManager.registerDriver(driver);
    38         // 2.连接到具体的数据库
    39         Connection conn = DriverManager.getConnection(url, user, password);
    40         System.out.println(conn);
    41     }
    42 
    43     /**
    44      * 第三种方式(推荐)
    45      * @throws Exception
    46      */
    47     @Test
    48     public void test3() throws Exception{
    49 
    50         // 1、通过得到字节码对象的方式加载静态代码块,从而注册驱动程序
    51         Class.forName("com.mysql.jdbc.Driver");
    52         // 2、连接到具体的数据库
    53         Connection conn = DriverManager.getConnection(url, user, password);
    54         System.out.println(conn);
    55     }
    56 }

    使用Statement对象执行sql语句

    1 url=jdbc:mysql://localhost:3306/day17
    2 user=root
    3 password=root
    4 driverClass=com.mysql.jdbc.Driver
     1 /**
     2  * Jdbc 工具类
     3  */
     4 public class JdbcUtil {
     5 
     6     private static String url = null;
     7     private static String user = null;
     8     private static String password = null;
     9     private static String driverClass = null;
    10 
    11     static{
    12         try {
    13             Properties props = new Properties();
    14             InputStream in = JdbcUtil.class.getResourceAsStream("/db.properties");
    15             props.load(in);
    16             url = props.getProperty("url");
    17             user = props.getProperty("user");
    18             password = props.getProperty("password");
    19             driverClass = props.getProperty("driverClass");
    20 
    21             //注册驱动程序
    22             Class.forName(driverClass);
    23         } catch (Exception e) {
    24             e.printStackTrace();
    25             System.out.println("驱程程序注册出错");
    26         }
    27     }
    28 
    29     /**
    30      * 获取连接对象
    31      */
    32     public static Connection getConnection(){
    33         try {
    34             Connection conn = DriverManager.getConnection(url, user, password);
    35             return conn;
    36         } catch (SQLException e) {
    37             e.printStackTrace();
    38             throw new RuntimeException(e);
    39         }
    40     }
    41 
    42     /**
    43      * 释放资源
    44      */
    45     public static void close(Connection conn, Statement stmt){
    46         if(stmt!=null){
    47             try {
    48                 stmt.close();
    49             } catch (SQLException e) {
    50                 e.printStackTrace();
    51                 throw new RuntimeException(e);
    52             }
    53         }
    54         if(conn!=null){
    55             try {
    56                 conn.close();
    57             } catch (SQLException e) {
    58                 e.printStackTrace();
    59                 throw new RuntimeException(e);
    60             }
    61         }
    62     }
    63 
    64     /**
    65      * 释放资源
    66      */
    67     public static void close(Connection conn, Statement stmt, ResultSet rs){
    68         if(rs!=null)
    69             try {
    70                 rs.close();
    71             } catch (SQLException e1) {
    72                 e1.printStackTrace();
    73                 throw new RuntimeException(e1);
    74             }
    75         if(stmt!=null){
    76             try {
    77                 stmt.close();
    78             } catch (SQLException e) {
    79                 e.printStackTrace();
    80                 throw new RuntimeException(e);
    81             }
    82         }
    83         if(conn!=null){
    84             try {
    85                 conn.close();
    86             } catch (SQLException e) {
    87                 e.printStackTrace();
    88                 throw new RuntimeException(e);
    89             }
    90         }
    91     }
    92 }

    执行DDL语句

    public class DDLJdbc {
    
        /**
         * 执行DDL语句(创建表)
         */
        @Test
        public void testCreate(){
            Statement stmt = null;
            Connection conn = null;
            try {
                // 获取连接对象
                conn = JdbcUtil.getConnection();
                // 创建Statement
                stmt = conn.createStatement();
                // 准备sql
                String sql = "CREATE TABLE student(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20),gender VARCHAR(2))";
                // 发送sql语句,执行sql语句,得到返回结果
                int count = stmt.executeUpdate(sql);
                System.out.println("影响了"+count+"行!");
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally{
                JdbcUtil.close(conn,stmt);
            }
        }
    
    }

    执行DML语句

     1 public class DMLJdbc {
     2 
     3     /**
     4      * 增加
     5      */
     6     @Test
     7     public void testInsert(){
     8         Connection conn = null;
     9         Statement stmt = null;
    10         try {
    11             // 获取连接对象
    12             conn = JdbcUtil.getConnection();
    13             // 创建Statement对象
    14             stmt = conn.createStatement();
    15             // 创建sql语句
    16             String sql = "INSERT INTO student(NAME,gender) VALUES('李四','女')";
    17             // 执行sql
    18             int count = stmt.executeUpdate(sql);
    19             System.out.println("影响了"+count+"行");
    20         } catch (Exception e) {
    21             e.printStackTrace();
    22             throw new RuntimeException(e);
    23         } finally{
    24             //关闭资源
    25             JdbcUtil.close(conn, stmt);
    26         }
    27     }
    28 
    29     /**
    30      * 删除
    31      */
    32     @Test
    33     public void testDelete(){
    34         Connection conn = null;
    35         Statement stmt = null;
    36         int id = 1;
    37         try {
    38             // 获取连接对象
    39             conn = JdbcUtil.getConnection();
    40             // 创建Statement对象
    41             stmt = conn.createStatement();
    42             // 创建sql语句
    43             String sql = "DELETE FROM student WHERE id="+id+"";
    44             System.out.println(sql);
    45             // 执行sql
    46             int count = stmt.executeUpdate(sql);
    47             System.out.println("影响了"+count+"行");
    48         } catch (Exception e) {
    49             e.printStackTrace();
    50             throw new RuntimeException(e);
    51         } finally{
    52             //关闭资源
    53             JdbcUtil.close(conn, stmt);
    54         }
    55     }
    56 
    57     /**
    58      * 修改
    59      */
    60     @Test
    61     public void testUpdate(){
    62         Connection conn = null;
    63         Statement stmt = null;
    64         String name = "test";
    65         int id = 1;
    66         try {
    67             // 获取连接对象
    68             conn = JdbcUtil.getConnection();
    69             // 创建Statement对象
    70             stmt = conn.createStatement();
    71             // 创建sql语句
    72             String sql = "UPDATE student SET NAME='"+name+"' WHERE id="+id+"";
    73             System.out.println(sql);
    74             // 执行sql
    75             int count = stmt.executeUpdate(sql);
    76             System.out.println("影响了"+count+"行");
    77         } catch (Exception e) {
    78             e.printStackTrace();
    79             throw new RuntimeException(e);
    80         } finally{
    81             //关闭资源
    82             JdbcUtil.close(conn, stmt);
    83         }
    84     }
    85 
    86 }

    执行DQL语句

     1 public class DQLJdbc {
     2 
     3     @Test
     4     public void testSelect(){
     5         Connection conn = null;
     6         Statement stmt = null;
     7         ResultSet rs = null;
     8         try{
     9             // 获取连接
    10             conn = JdbcUtil.getConnection();
    11             // 创建Statement
    12             stmt = conn.createStatement();
    13             // 准备sql
    14             String sql = "SELECT * FROM student";
    15             // 执行sql
    16             rs = stmt.executeQuery(sql);
    17             System.out.println(rs);
    18             //遍历结果
    19             while (rs.next()){
    20                 int id = rs.getInt("id");
    21                 String name = rs.getString("name");
    22                 String gender = rs.getString("gender");
    23                 System.out.println(id+","+name+","+gender);
    24             }
    25         }catch(Exception e){
    26             e.printStackTrace();
    27             throw new RuntimeException(e);
    28         }finally{
    29             JdbcUtil.close(conn, stmt,rs);
    30         }
    31     }
    32 }

     使用PreparedStatement对象执行sql语句

      1 public class PreparedJdbc {
      2 
      3     /**
      4      * 增加
      5      */
      6     @Test
      7     public void testInsert() {
      8         Connection conn = null;
      9         PreparedStatement stmt = null;
     10         try {
     11             // 获取连接对象
     12             conn = JdbcUtil.getConnection();
     13             // 准备预编译的sql
     14             String sql = "INSERT INTO student(NAME,gender) VALUES(?,?)";
     15             // 执行预编译sql语句(检查语法)
     16             stmt = conn.prepareStatement(sql);
     17             // 设置参数值
     18             stmt.setString(1, "李四");
     19             stmt.setString(2, "男");
     20             // 发送参数,执行sql
     21             int count = stmt.executeUpdate();
     22             System.out.println("影响了"+count+"行");
     23         } catch (Exception e) {
     24             e.printStackTrace();
     25             throw new RuntimeException(e);
     26         } finally {
     27             JdbcUtil.close(conn, stmt);
     28         }
     29     }
     30 
     31     /**
     32      * 修改
     33      */
     34     @Test
     35     public void testUpdate() {
     36         Connection conn = null;
     37         PreparedStatement stmt = null;
     38         try {
     39             // 获取连接对象
     40             conn = JdbcUtil.getConnection();
     41             // 准备预编译的sql
     42             String sql = "UPDATE student SET NAME=? WHERE id=?";
     43             // 预编译sql语句(检查语法)
     44             stmt = conn.prepareStatement(sql);
     45             // 设置参数值
     46             stmt.setString(1, "王五");
     47             stmt.setInt(2, 3);
     48             // 发送参数,执行sql
     49             int count = stmt.executeUpdate();
     50             System.out.println("影响了"+count+"行");
     51         } catch (Exception e) {
     52             e.printStackTrace();
     53             throw new RuntimeException(e);
     54         } finally {
     55             JdbcUtil.close(conn, stmt);
     56         }
     57     }
     58 
     59     /**
     60      * 删除
     61      */
     62     @Test
     63     public void testDelete() {
     64         Connection conn = null;
     65         PreparedStatement stmt = null;
     66         try {
     67             // 获取连接对象
     68             conn = JdbcUtil.getConnection();
     69             // 准备预编译的sql
     70             String sql = "DELETE FROM student WHERE id=?";
     71             // 预编译sql语句(检查语法)
     72             stmt = conn.prepareStatement(sql);
     73             // 设置参数值
     74             stmt.setInt(1, 9);
     75             // 发送参数,执行sql
     76             int count = stmt.executeUpdate();
     77             System.out.println("影响了"+count+"行");
     78         } catch (Exception e) {
     79             e.printStackTrace();
     80             throw new RuntimeException(e);
     81         } finally {
     82             JdbcUtil.close(conn, stmt);
     83         }
     84     }
     85 
     86     /**
     87      * 查询
     88      */
     89     @Test
     90     public void testQuery() {
     91         Connection conn = null;
     92         PreparedStatement stmt = null;
     93         ResultSet rs = null;
     94         try {
     95             // 获取连接对象
     96             conn = JdbcUtil.getConnection();
     97             // 准备预编译的sql
     98             String sql = "SELECT * FROM student";
     99             // 预编译
    100             stmt = conn.prepareStatement(sql);
    101             // 执行sql
    102             rs = stmt.executeQuery();
    103             //5.遍历rs
    104             while(rs.next()){
    105                 int id = rs.getInt("id");
    106                 String name = rs.getString("name");
    107                 String gender = rs.getString("gender");
    108                 System.out.println(id+","+name+","+gender);
    109             }
    110 
    111         } catch (Exception e) {
    112             e.printStackTrace();
    113             throw new RuntimeException(e);
    114         } finally {
    115             //关闭资源
    116             JdbcUtil.close(conn,stmt,rs);
    117         }
    118     }
    119 }
  • 相关阅读:
    MD支持新标签跳转
    线上问题cpu100处理记录
    OpenShift 4.6方式下OperatorHub的变化
    OpenShift 4.5.7 版本基础镜像下载
    GLPI企业使用(一),连接AD域,LDAP登录。
    GLPI配置文件说明:默认权限组
    企业服务器规划
    港股通转托管
    mui实现下拉刷新以及click事件无法响应问题
    asp.net core+websocket实现实时通信
  • 原文地址:https://www.cnblogs.com/ysdrzp/p/9943352.html
Copyright © 2011-2022 走看看