• JBDC的使用


    1. JDBC介绍

    JDBC(Java Database Connectivity)是一个独立于特定数据库管理系统、通用的SQL数据库存取和操作的公共接口(一组API),定义了用来访问数据库的标准Java类库,(java.sql,javax.sql)使用这些类库可以以一种标准的方法、方便地访问数据库资源。JDBC为访问不同的数据库提供了一种统一的途径,为开发者屏蔽了一些细节问题。JDBC的目标是使Java程序员使用JDBC可以连接任何提供了JDBC驱动程序的数据库系统,这样就使得程序员无需对特定的数据库系统的特点有过多的了解,从而大大简化和加快了开发过程。如果没有JDBC,那么Java程序访问数据库时是这样的:
    在这里插入图片描述
    有了JDBC,Java程序访问数据库时是这样的:
    在这里插入图片描述
    JDBC接口(API)包括两个层次:

    • 面向应用的API:Java API,抽象接口,供应用程序开发人员使用(连接数据库,执行SQL语句,获得结果)。
    • 面向数据库的API:Java Driver API,供开发商开发数据库驱动程序用。

    JDBC程序编写步骤:
    在这里插入图片描述

    2. 获取数据库连接

    获取连接的四要素:

    1. JDBC驱动
      在当前项目模块下建里lib目录,
      在这里插入图片描述
      然后按右键,选择Add as Library选项。
      在这里插入图片描述

    2. URL
      JDBC URL的标准由三部分组成,各部分间用冒号分隔。

    • jdbc:子协议:子名称
      协议:JDBC URL中的协议总是jdbc
      子协议:子协议用于标识一个数据库驱动程序
    • 子名称:一种标识数据库的方法。子名称可以依不同的子协议而变化,用子名称的目的是为了定位数据库提供足够的信息。包含主机名(对应服务端的ip地址),端口号,数据库名
    1. 用户名字和密码
      栗子
    public class GetConnection {
        @Test
        public void test1() {
            //获取连接方式一
            try {
                //1. 提供java.sql.jdbc.Driver的实现类
                Driver driver = null;
                driver = new com.mysql.jdbc.Driver();
    
                //2.提供url
                String url = "jdbc:mysql://localhost:3306/test";
    
                //3.提供用户和密码
                Properties properties = new Properties();
                properties.put("user", "root");
                properties.put("password", "123");
    
                //获取连接
                Connection connect = driver.connect(url, properties);
                System.out.println(connect);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    
        //方式二
        @Test
        public void test() {
    
            try {
                //1.实例化Driver
                String className = "com.mysql.jdbc.Driver";
                Class<?> clazz = Class.forName(className);
                Driver driver = (Driver) clazz.newInstance();
    
                //2.提供url
                String url = "jdbc:mysql://localhost:3306/test";
    
                //3.提供用户和密码
                Properties properties = new Properties();
                properties.put("user", "root");
                properties.put("password", "123");
    
                //获取连接
                Connection connect = driver.connect(url, properties);
                System.out.println(connect);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    
        //方式三
        @Test
        public void test3(){
            //mysql连接的4要素
            String driverName = "com.mysql.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/test";
            String user = "root";
            String password = "123";
            try {
                //1.实例化Driver
                Class<?> clazz = Class.forName(driverName);
                Driver driver = (Driver)clazz.newInstance();
    
                //2.注册驱动
                DriverManager.registerDriver(driver);
    
                //3.获取连接
                Connection connection = DriverManager.getConnection(url, user, password);
                System.out.println(connection);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    
        //方式四
        @Test
        public void test4(){
            //mysql连接的4要素
            String driverName = "com.mysql.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/test";
            String user = "root";
            String password = "123";
            try {
                //1.实例化Driver
    //            Class<?> clazz = Class.forName(driverName);
    //            Driver driver = (Driver)clazz.newInstance();
    
                //2.注册驱动
                Class.forName(driverName);
    
                //3.获取连接
                Connection connection = DriverManager.getConnection(url, user, password);
                System.out.println(connection);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }  catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        //方式五:加载配置文件的方式
        @Test
        public void test5(){
            InputStream in = null;
            Properties ps = null;
            try {
                in = GetConnection.class.getClassLoader().getResourceAsStream("jdbc.properties");
                ps = new Properties();
                ps.load(in);
    
                //读取配置文件
                String user = ps.getProperty("user");
                String password = ps.getProperty("password");
                String url = ps.getProperty("url");
                String driverClass = ps.getProperty("driverClass");
    
                //加载驱动
                Class.forName(driverClass);
    
                //获取连接
                Connection connection = DriverManager.getConnection(url, user, password);
                System.out.println(connection);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
    
    
        }
    
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148

    3. 实现数据库CURD

    数据库连接被用于向数据库服务器发送命令和 SQL 语句,并接受数据库服务器返回的结果。其实一个数据库连接就是一个Socket连接。
    在 java.sql 包中有 3 个接口分别定义了对数据库的调用的不同方式:

    • Statement:用于执行静态 SQL 语句并返回它所生成结果的对象。
    • PrepatedStatement:SQL 语句被预编译并存储在此对象中,可以使用此对象多次高效地执行该句。
    • CallableStatement:用于执行 SQL 存储过程

    Statement版
    使用Statement来实现CURD有如下的弊端:
    问题一:存在拼串操作,繁琐
    问题二:存在SQL注入问题

    public class StatementTest {
    
    
        public static void main(String ...args){
            Scanner scan = new Scanner(System.in);
            System.out.println("请输入用户名:");
            String userName = scan.nextLine();
            System.out.println("请输入密码:");
            String password = scan.nextLine();
            //String sql = "SELECT user,password FROM user_table WHERE user = 'aa' OR ( true OR ( true AND password = '123'))";
            String sql = "SELECT user,password FROM user_table WHERE user = '" + userName + "' AND password = '" + password + "'";
            System.out.println(sql);
            User user = get(sql, User.class);
            if(user != null){
                System.out.println(user);
            }else{
                System.out.println("登录失败!!");
            }
    
        }
        public static <T> T get(String sql, Class<T> clazz){
            T t = null;
            Connection conn = null;
            Statement stat = null;
            ResultSet rs = null;
            try{
                //加载配置文件
                InputStream in = StatementTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
                Properties ps = new Properties();
                ps.load(in);
    
                //获取配置信息
                String driverClass = ps.getProperty("driverClass");
                String url = ps.getProperty("url");
                String user = ps.getProperty("user");
                String password = ps.getProperty("password");
    
                //注册驱动
                Class.forName(driverClass);
    
                //获取连接
                conn = DriverManager.getConnection(url, user, password);
    
                //创建Statement对象,并执行sql
                stat = conn.createStatement();
                rs = stat.executeQuery(sql);
    
                //获取元数据
                ResultSetMetaData metaData = rs.getMetaData();
                //获取列数
                int colCnt = metaData.getColumnCount();
    
                if(rs.next()){
                    t = clazz.newInstance();
                    for (int i = 0; i < colCnt; i++) {
                        //获取列的别名
                        String label = metaData.getColumnLabel(i + 1);
                        //依据列名获取数据
                        Object colVal = rs.getObject(label);
    
                        //属性值封装进对象
                        Field field = clazz.getDeclaredField(label);
                        field.setAccessible(true);
                        field.set(t,colVal);
                    }
    
                }
                return t;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } finally {
               if(rs != null){
                   try {
                       rs.close();
                   } catch (SQLException e) {
                       e.printStackTrace();
                   }
               }
               if(stat != null){
                   try {
                       stat.close();
                   } catch (SQLException e) {
                       e.printStackTrace();
                   }
               }
    
               if(conn != null){
                   try {
                       conn.close();
                   } catch (SQLException e) {
                       e.printStackTrace();
                   }
               }
            }
            return null;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108

    PreparedStatement版
    可以通过调用 Connection 对象的 preparedStatement(String sql) 方法获取 PreparedStatement 对象
    PreparedStatement 接口是 Statement 的子接口,它表示一条预编译过的 SQL 语句。
    PreparedStatement 对象所代表的 SQL 语句中的参数用问号(?)来表示,调用 PreparedStatement 对象的setXxx() 方法来设置这些参数. setXxx() 方法有两个参数,第一个参数是要设置的 SQL 语句中的参数的索引(从 1开始),第二个是设置的 SQL 语句中的参数的值。

    public class PreparedStatementTest {
    
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            System.out.println("请输入用户名:");
            String userName = scan.nextLine();
            System.out.println("请输入密码:");
            String password = scan.nextLine();
            //String sql = "SELECT user,password FROM user_table WHERE user = 'aa' OR ( true OR ( true AND password = '123'))";
            String sql = "SELECT user,password FROM user_table WHERE user = '" + userName + "' AND password = '" + password + "'";
            System.out.println(sql);
            User user = get(sql, User.class);
            if(user != null){
                System.out.println(user);
            }else{
                System.out.println("登录失败!!");
            }
        }
    
        public static <T> T get(String sql, Class clazz,String ... args){
            T t = null;
            Connection conn = null;
            Statement st = null;
            ResultSet rs = null;
    
            try {
                InputStream is = PreparedStatementTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
                Properties ps = new Properties();
                ps.load(is);
                //获取配置信息
                String driverClass = ps.getProperty("driverClass");
                String url = ps.getProperty("url");
                String user = ps.getProperty("user");
                String password = ps.getProperty("password");
    
                //注册驱动
                Class.forName(driverClass);
    
                //获取连接
                conn = DriverManager.getConnection(url, user, password);
    
                PreparedStatement pres = conn.prepareStatement(sql);
                for (int i = 0; i < args.length; i++) {
                    pres.setObject(i + 1, args[i]);
                }
                rs = pres.executeQuery();
                //获取元数据
                ResultSetMetaData metaData = rs.getMetaData();
                //获取列数
                int colCnt = metaData.getColumnCount();
    
                if(rs.next()){
                    t = (T) clazz.newInstance();
                    for (int i = 0; i < colCnt; i++) {
                        //获取列的别名
                        String label = metaData.getColumnLabel(i + 1);
                        //依据列名获取数据
                        Object colVal = rs.getObject(label);
    
                        //属性值封装进对象
                        Field field = clazz.getDeclaredField(label);
                        field.setAccessible(true);
                        field.set(t,colVal);
                    }
    
                }
                return t;
    
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85

    4. ResultSet与ResultSetMetaData

    ResultSet

    • 查询需要调用PreparedStatement 的 executeQuery() 方法,查询结果是一个ResultSet 对象
    • ResultSet 对象以逻辑表格的形式封装了执行数据库操作的结果集,ResultSet 接口由数据库厂商提供实现
    • ResultSet 返回的实际上就是一张数据表。有一个指针指向数据表的第一条记录的前面。
    • ResultSet 对象维护了一个指向当前数据行的游标,初始的时候,游标在第一行之前,可以通过ResultSet 对象的 next() 方法移动到下一行。调用 next()方法检测下一行是否有效。若有效,该方法返回 true,且指针下移。
    • 相当于Iterator对象的 hasNext() 和 next() 方法的结合体。

    ResultSetMetaData

    • 可用于获取关于 ResultSet 对象中列的类型和属性信息的对象
    • ResultSetMetaData meta = rs.getMetaData();
      常用方法:
      getColumnName(int column):获取指定列的名称
      getColumnLabel(int column):获取指定列的别名
      getColumnCount():返回当前 ResultSet 对象中的列数。
      getColumnTypeName(int column):检索指定列的数据库特定的类型名称。
      getColumnDisplaySize(int column):指示指定列的最大标准宽度,以字符为单位。
      isNullable(int column):指示指定列中的值是否可以为 null。
      isAutoIncrement(int column):指示是否自动为指定列进行编号,这样这些列仍然是只读的。

    5. 批量插入

    当需要成批插入或者更新记录时,可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处
    理。通常情况下比单独提交处理更有效率
    JDBC的批量处理语句包括下面三个方法:
    addBatch(String):添加需要批量处理的SQL语句或是参数;
    executeBatch():执行批量处理语句;
    clearBatch():清空缓存的数据

    public class BatchProccessTest {
        @Test
        public void test1() throws SQLException {
            Connection conn = JDBCUtils.getConnection();
            String sql = "INSERT INTO goods(name) VALUES (?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            long start = System.currentTimeMillis();
            for (int i = 0; i < 20000; i++) {
                ps.setObject(1, "name_" + i);
                ps.executeUpdate();
            }
            long end = System.currentTimeMillis();
            System.out.println("共用时:" + (end - start));
        }
    
        @Test
        public void test2() throws SQLException {
            Connection conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);
            String sql = "INSERT INTO goods(name) VALUES (?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            long start = System.currentTimeMillis();
            for (int i = 0; i < 20000; i++) {
                ps.setObject(1, "name_" + i);
                ps.addBatch();
                if((i + 1) % 500 == 0){
                    ps.executeBatch();
                    ps.clearBatch();
                }
            }
            conn.commit();
            long end = System.currentTimeMillis();
            System.out.println("共用时:" + (end - start));
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    6. 数据库连接池

    在使用开发基于数据库的web程序时,传统的模式基本是按以下步骤:

    1. 在主程序(如servlet、beans)中建立数据库连接
    2. 进行sql操作
    3. 断开数据库连接
      这种模式开发,存在的问题:
    • 普通的JDBC数据库连接使用 DriverManager 来获取,每次向数据库建立连接的时候都要Connection
      加载到内存中,再验证用户名和密码(得花费0.05s~1s的时间)。需要数据库连接的时候,就向数据库要求一个,执行完成后再断开连接。这样的方式将会消耗大量的资源和时间。数据库的连接资源并没有得到很好的重复利用。
    • 对于每一次数据库连接,使用完后都得断开。否则,如果程序出现异常而未能关闭,将会导致数据库系统中的内存泄漏,最终将导致重启数据库。(回忆:何为Java的内存泄漏?)
    • 这种开发不能控制被创建的连接对象数,系统资源会被毫无顾及的分配出去,如连接过多,也可能导致内存泄漏,服务器崩溃。
      为解决传统开发中的数据库连接问题,可以采用数据库连接池技术。数据库连接池的基本思想:就是为数据库连接建立一个“缓冲池”。预先在缓冲池中放入一定数量的连接,当需要建立数据库连接时,只需从“缓冲池”中取出一个,使用完毕之后再放回去。数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是重新建立一个。数据库连接池在初始化时将创建一定数量的数据库连接放到连接池中,这些数据库连接的数量是由最小数据库连接数来设定的。无论这些数据库连接是否被使用,连接池都将一直保证至少拥有这么多的连接数量。连接池的最大数据库连接数量限定了这个连接池能占有的最大连接数,当应用程序向连接池请求的连接数超过最大连接数量时,这些请求将被加入到等待队列中。
      JDBC 的数据库连接池使用 javax.sql.DataSource 来表示,DataSource 只是一个接口,该接口通常由服务器(Weblogic, WebSphere, Tomcat)提供实现,也有一些开源组织提供实现:
    • DBCP 是Apache提供的数据库连接池。tomcat 服务器自带dbcp数据库连接池。速度相对c3p0较快,但因自身存在BUG,Hibernate3已不再提供支持。
    • C3P0 是一个开源组织提供的一个数据库连接池,速度相对较慢,稳定性还可以。hibernate官方推荐使用Proxool 是sourceforge下的一个开源项目数据库连接池,有监控连接池状态的功能,稳定性c3p0差一点。
    • BoneCP 是一个开源组织提供的数据库连接池,速度快
    • Druid 是阿里提供的数据库连接池,据说是集DBCP 、C3P0 、Proxool 优点于一身的数据库连接池,但是速度不确定是否有BoneCP快。

    C3P0连接池

    public class C3P0Test {
        @Test
        public void test1() throws PropertyVetoException, SQLException {
            //方式一
            ComboPooledDataSource cpds = new ComboPooledDataSource();
            cpds.setDriverClass("com.mysql.jdbc.Driver");
            cpds.setJdbcUrl("jdbc:mysql://localhost:3306/test");
            cpds.setUser("root");
            cpds.setPassword("123");
    
            cpds.setMaxPoolSize(10);
            Connection conn = cpds.getConnection();
            System.out.println(conn);
        }
    
    
        @Test
        public void test2() throws SQLException {
            //方式二
            ComboPooledDataSource cpds = new ComboPooledDataSource("c3p0");
            Connection conn = cpds.getConnection();
            System.out.println(conn);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    配置文件c3p0-config.xml如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <c3p0-config>
    
    	<named-config name="hellc3p0">
    		<!-- 提供获取连接的4个基本信息 -->
    		<property name="driverClass">com.mysql.jdbc.Driver</property>
    		<property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
    		<property name="user">root</property>
    		<property name="password">123</property>
    		
    		<!-- 进行数据库连接池管理的基本信息 -->
    		<!-- 当数据库连接池中的连接数不够时,c3p0一次性向数据库服务器申请的连接数 -->
    		<property name="acquireIncrement">5</property>
    		<!-- c3p0数据库连接池中初始化时的连接数 -->
    		<property name="initialPoolSize">10</property>
    		<!-- c3p0数据库连接池维护的最少连接数 -->
    		<property name="minPoolSize">10</property>
    		<!-- c3p0数据库连接池维护的最多的连接数 -->
    		<property name="maxPoolSize">100</property>
    		<!-- c3p0数据库连接池最多维护的Statement的个数 -->
    		<property name="maxStatements">50</property>
    		<!-- 每个连接中可以最多使用的Statement的个数 -->
    		<property name="maxStatementsPerConnection">2</property>
    
    	</named-config>
    </c3p0-config>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    dbcp连接池

    public class dbcpTest {
        @Test
        public void test1() throws SQLException {
            //方式一
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://localhost:3306/test");
            dataSource.setUsername("root");
            dataSource.setPassword("123");
    
            Connection conn = dataSource.getConnection();
            System.out.println(conn);
        }
        @Test
        public void test2() throws Exception {
            //方式二
            FileInputStream is = new FileInputStream("src/dbcp.properties");
            Properties ps = new Properties();
            ps.load(is);
    
            DataSource dataSource = BasicDataSourceFactory.createDataSource(ps);
    
            Connection conn = dataSource.getConnection();
            System.out.println(conn);
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    dbcp.properties配置文件:

    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/test
    username=root
    password=123
    
    • 1
    • 2
    • 3
    • 4

    Druid(德鲁伊)数据库连接池

    public class DruidTest {
        @Test
        public void test() throws Exception {
            Properties pros = new Properties();
            InputStream is = new FileInputStream("src/druid.properties");
            pros.load(is);
    
            DataSource dataSource = DruidDataSourceFactory.createDataSource(pros);
    
            Connection conn = dataSource.getConnection();
            System.out.println(conn);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    druid.properties配置文件

    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/test
    username=root
    password=123
    
    • 1
    • 2
    • 3
    • 4
  • 相关阅读:
    BP神经网络算法基本原理,bp神经网络算法详解
    使用虚拟机安装ikuai软路由系统,搭建pppoe拨号服务器
    ChatGPT :十几个国内免费可用 ChatGPT 网页版
    (附源码)spring boot宠物医院管理系统 毕业设计 180923
    Linux查找软件安装在哪里
    Flutter开发 - 监听滑动列表(解决特殊列表严重占用内存问题),并在滑动时暂停动画,暂停还未完成的下载操作,列表停止后恢复
    第4章 决策树
    微信PC端有了新功能,快来看看你知不知道
    ubuntu16编译linux源码内核
    从手动操作到自动化管理,如何实现企业身份业务全面自动化?
  • 原文地址:https://blog.csdn.net/weixin_44335707/article/details/125468539