zoukankan      html  css  js  c++  java
  • JDBC详解系列(一)之流程

    ---来自我的CSDN博客---


    JDBC概述

      使用JDBC也挺长时间了,最近因为想学习mybatis的源码,因此打算重新复习一下JDBC的使用。

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

      也就是说JDBC是SUN公司提出来的一系列规范,但它只定义了接口规范,具体的实现则交给各个数据库的厂商去做。这类似以前的软件要调用打印机的时候都要自己去给各种类型的打印机实现驱动,但微软在操作系统定义了打印机驱动接口,由各个打印机厂商去实现,而软件供应商只需要调用接口即可(不然每个数据库都要自己去实现驱动,会累死的)。我想这也符合JAVA跨平台的思想,实现“Write once, run anywhere!”。

    JDBC使用详解

      先上代码,一个简单的连接,查询用户信息:

    /**
     * 如果你要使用我的代码,在此之前请在mysql创建jdbc_test数据库,并建立student表,两个字段,name和age
     */
    public class JDBCTest {
        /**
         * 数据库相关参数
         */
        //这是驱动名称,此例子中我们加载的是mysql的驱动,在之前需要导入mysql的驱动jar包
        public static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    
        //连接数据库的url,各个数据库厂商不一样,此处为mysql的;后面是创建的数据库名称
        public static final String JDBC_URL = "jdbc:mysql://localhost:3306/jdbc_test";
    
        //连接数据库所需账户名
        public static final String JDBC_USERNAME = "root";
    
        //用户名对应的密码,我的mysql密码是123456
        public static final String JDBC_PASSWORD ="123456";
    
    
        public static void main(String[] args) {
            List<Student> students = new ArrayList<Student>();
    
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
    
            try {
                //第一步:加载Driver类,注册数据库驱动
                Class.forName(JDBC_DRIVER);
                //第二步:通过DriverManager,使用url,用户名和密码建立连接(Connection)
                connection = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
                //第三步:通过Connection,使用sql语句打开Statement对象;
                preparedStatement = connection.prepareStatement("select * from student where age =?");
               //传入参数,之所以这样是为了防止sql注入
                preparedStatement.setInt(1, 18);
                //第四步:执行语句,将结果返回resultSet
                resultSet = preparedStatement.executeQuery();
                //第五步:对结果进行处理
                while (resultSet.next()){
                    String name = resultSet.getString("name");
                    int age = resultSet.getInt("age");
    
                    Student student = new Student();
                    student.setAge(age);
                    student.setName(name);
                    students.add(student);
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                //第六步:倒叙释放资源resultSet-》preparedStatement-》connection
                try {
                    if (resultSet!=null && !resultSet.isClosed()){
                        resultSet.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
    
                try {
                    if(preparedStatement!=null && 
                        !preparedStatement.isClosed()){
                        preparedStatement.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
    
                try {
                    if(connection!=null && connection.isClosed()){
                        connection.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
    
            for (Student student:students
                 ) {
                System.out.println(student.getName()+"="+student.getAge());
            }
    
        }
    }
    
    

      以上就是JDBC查询的基本连接过程,后续一些复杂的数据库操作过程只不过是在上面进行一些增改而已。大体步骤如注释:

    JDBC流程:
    第一步:加载Driver类,注册数据库驱动;
    第二步:通过DriverManager,使用url,用户名和密码建立连接(Connection);
    第三步:通过Connection,使用sql语句打开Statement对象;
    第四步:执行语句,将结果返回resultSet;
    第五步:对结果resultSet进行处理;
    第六步:倒叙释放资源resultSet-》preparedStatement-》connection。

      如果是删除,修改和插入,使用executeUpdate()即可:

    /**
     * 如果你要使用我的代码,在此之前请在mysql创建jdbc_test数据库,并建立student表,两个字段,name和age
     */
    public class JDBCTest {
        /**
         * 数据库相关参数
         */
        //这是驱动名称,此例子中我们加载的是mysql的驱动,在之前需要导入mysql的驱动jar包
        public static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    
        //连接数据库的url,各个数据库厂商不一样,此处为mysql的;后面是创建的数据库名称
        public static final String JDBC_URL = "jdbc:mysql://localhost:3306/jdbc_test";
    
        //连接数据库所需账户名
        public static final String JDBC_USERNAME = "root";
    
        //用户名对应的密码,我的mysql密码是123456
        public static final String JDBC_PASSWORD = "123456";
    
    
        @Test
        public void testUpdate() {
            Connection connection = null;
            PreparedStatement preparedStatement = null;
    
            try {
                //第一步:加载Driver类,注册数据库驱动
                Class.forName(JDBC_DRIVER);
                //第二步:通过DriverManager,使用url,用户名和密码建立连接(Connection)
                connection = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
                //第三步:通过Connection,使用sql语句打开Statement对象;
                preparedStatement = connection.prepareStatement("UPDATE student SET age=20 WHERE name=?");
                //传入参数,之所以这样是为了防止sql注入
                preparedStatement.setString(1, "xiaoming");
                //第四步:执行语句,将结果返回resultSet
                int count = preparedStatement.executeUpdate();
                //第五步:对结果进行处理
                System.out.println(count);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                //第六步:倒叙释放资源resultSet-》preparedStatement-》connection
    
                try {
                    if (preparedStatement != null && 
                        !preparedStatement.isClosed()) {
                        preparedStatement.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
    
                try {
                    if (connection != null && connection.isClosed()) {
                        connection.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

      以及批量操作:

    @Test
        /**
         * 测试批量操作
         */
        public void testBatch() {
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            String insertSql = "insert into student values(?,?)";
            try {
                //第一步:加载Driver类,注册数据库驱动
                Class.forName(JDBC_DRIVER);
                //第二步:通过DriverManager,使用url,用户名和密码建立连接(Connection)
                connection = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
                //第三步:通过Connection,使用sql语句打开Statement对象;
                preparedStatement = connection.prepareStatement(insertSql);
                //传入参数,之所以这样是为了防止sql注入
              for(int i=0;i<10;i++){
                  preparedStatement.setString(1,100+i+"user");
                  preparedStatement.setInt(2,100+i);
                  preparedStatement.addBatch();
              }
                //第四步:执行语句,将结果返回resultSet
                int[] count = preparedStatement.executeBatch();
                //第五步:对结果进行处理
                System.out.println(count);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                //第六步:倒叙释放资源resultSet-》preparedStatement-》connection
    
                try {
                    if (preparedStatement != null && 
                        !preparedStatement.isClosed()) {
                        preparedStatement.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
    
                try {
                    if (connection != null && connection.isClosed()) {
                        connection.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    

      今天大概介绍了JDBC连接数据库进行操作的一些具体的流程,后面我会对流程上的各个步骤进行分析,以便在后续学习mybatis源码时有一个更深刻的理解。

    ---[来自我的CSDN博客](http://blog.csdn.net/weixin_37139197/article/details/78838091)---

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    1.14验证码 彩票
    String代码示例
    1.13作业
    控制台输入人数和分数 自动判断最高分最低分
    对矩阵进行转置运算
    16、输入三角形的三个边,求其面积
    02、
    15、判断字符串是否回文——字符串
    14、求出最大元素的下标及地址值——数组
    13、字符串在指定的地方以及元素个数实行逆置——字符串
  • 原文地址:https://www.cnblogs.com/homejim/p/8068199.html
Copyright © 2011-2022 走看看