当前位置:网站首页>Database connection pool & dbutils

Database connection pool & dbutils

2022-07-24 00:35:00 Qing

Database connection pool

Connection pool Introduction

What is connection pooling

  • In development “ Obtain a connection ” or “ Release resources ” They are two processes that consume system resources very much , To solve this kind of performance problem , Usually we use connection pooling technology , To share the connection Connection. So we don't have to create a connection every time 、 Release the connection , These operations are handed over to the connection pool .

The benefits of connection pooling

  • Pool to manage Connection, It can be reused Connection. When used Connection after , call Connection Of close() Methods don't really close Connection, But the Connection“ The return ” Feed pool .

JDBC Mode and connection pool mode

  • Ordinary JDBC The way

 Insert picture description here

  • Connection pool way

 Insert picture description here

How to use database connection pool

Java Provides a common interface for the database connection pool :javax.sql.DataSource, Each manufacturer needs to make its own connection pool implement this interface . Such an application can easily switch the connection pools of different manufacturers .
Common connection pools are DBCP Connection pool ,C3P0 Connection pool ,Druid Connection pool

Data preparation


# Create database 
create database db6 character set utf-8;

# Using a database 
use db6;

# Create an employee table 
create table employee(
         eid int PRIMARY KEY auto_increment,    
		ename VARCHAR(20),   --  Employee name 
		age int,      --  Age of employee 
		sex VARCHAR(6),  --  Gender of employees 
		salary DOUBLE,   --  salary 
		empdate date     --  Date of entry 
);

#  insert data 
insert into employee(eid,ename,age,sex,salary,empdate)
VALUES(null,' Li qingzhao ',22,' Woman ',4000,'2018-11-12');
insert into employee(eid,ename,age,sex,salary,empdate)
VALUES(null,' Lin daiyu ',20,' Woman ',5000,'2019-03-14');
insert into employee(eid,ename,age,sex,salary,empdate)
VALUES(null,' Du Fu ',40,' male ',6000,'2020-01-01');
insert into employee(eid,ename,age,sex,salary,empdate)
VALUES(null,' Li Bai ',25,' male ',3000,'2017-10-01');

DBCP Connection pool

DBCP It's also an open source connection pool , yes Apache One of the members , It is also common in enterprise development ,tomcat Built in connection pool

Create project Import jar package

1) Put these two jar Package is added to the myjar In the folder
 Insert picture description here 2) add to myjar Library to project dependencies

 Insert picture description here

Write a tool class

  • Tool class for connecting database tables , use DBCP Connection pool to complete
    Java A rule interface for connection pooling is provided in :DataSource, It is java Connection pool provided in , As DriverManager An alternative to a tool
    stay DBCP Provided in DataSource Implementation class of interface , The specific connection pool we're going to use BasicDataSource class
package com.utils;

import org.apache.commons.dbcp.BasicDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBCPUtils {
    
// 1. Define constants   Save information about the database connection 
    public static final String DRIVERNAME = "com.mysql.jdbc.Driver" ;
    public static final String URL = "jdbc:mysql://localhost:3306/db6?characterEncoding=UTF-8" ;
    public static final String USERNAME = "root" ;
    public static final String PASSWORD = "123456" ;

// 2. Create connection pool object ( Yes DBCP Implementation class provided )
    public static BasicDataSource dataSource = new BasicDataSource();

// 3. Use static code blocks to configure 
    static {
    
        dataSource.setDriverClassName(DRIVERNAME);
        dataSource.setUrl(URL);
        dataSource.setUsername(USERNAME);
        dataSource.setPassword(PASSWORD);
    }

// 4. How to get the connection 
    public static Connection getConnection() throws SQLException {
    
//  Get from the connection pool 
        Connection connection = dataSource.getConnection();
        return connection;
    }

//  Release resources 
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
    
        if (connection != null && statement != null && resultSet != null){
    
            try {
    
                resultSet.close();
                statement.close();
//  Return connection 
                connection.close();
            } catch (SQLException throwables) {
    
                throwables.printStackTrace();
            }
            
        }
    }
}

Test class :

package com.utils.testpool;

import com.utils.DBCPUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestDBCP {
    

    /** *  test DBCP Connection pool  * @param args */
    public static void main(String[] args) throws SQLException {
    

// 1. from DBCP Get the connection from the connection pool 
        Connection connection = DBCPUtils.getConnection();

// 2. obtain Statement object 
        Statement statement = connection.createStatement();

// 3. Check all employees 
        String sql = "select ename from employee" ;
        ResultSet resultSet = statement.executeQuery(sql);

// 4. Processing result set 
        while (resultSet.next()){
    
            String ename = resultSet.getString("ename") ;
            System.out.println(" Employee name :" + ename);
        }

// 5. Release resources 
        DBCPUtils.close(connection,statement,resultSet);

    }
}

Common configuration items

attribute describe
driverClassName Database driver name
url Database address
username user name
password password
maxActive Maximum number of connections
maxIdle Maximum free connection
minIdle Minimum free connection
initialSize Initialize connection

C3P0 Connection pool

C3P0 It's an open source JDBC Connection pool , Support JDBC3 Normative and JDBC2 Standard extension of . Which of its open source projects currently use Hibernate、Spring etc.

Import jar Packages and configuration files

 Insert picture description here
 Insert picture description here

 Insert picture description here

Common configuration

 Insert picture description here

Druid Connection pool

Druid( Druid ) Is a database connection pool developed by alibaba that it claims was created for surveillance ,Druid Is the best database connection pool available ,Druid Is the best database connection pool available . In the functional 、 performance 、 extensibility , All over the other database connection pool , At the same time, log monitoring is added , It's a good monitor DB Pool connection and SQL Implementation of

Import jar Packages and configuration files

1) Import jar package
 Insert picture description here

2) Import profile

  • yes properties Formal
  • You can call it anything , It can be placed in any directory , We put it together resources Resource directory

 Insert picture description here

To write Druid Tool class

  • Get database connection pool object
    Through the factory DruidDataSourceFactory Class createDataSource Method
    createDataSource(Properties p) The method parameter can be an attribute set object
package com.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.*;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DruidUtils {
    

// 1. Define member variables 
    public static DataSource dataSource;

// 2. Static code block 
    static {
    
//  Create property set object 
       try {
    
        Properties p = new Properties();
// Druid Connection pool cannot load configuration file actively , Need to execute documents 
        InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");

// Properties object   Of Load Method , Read configuration information from byte stream 

        p.load(inputStream);

//  Get the connection pool object through the factory class 
           dataSource=DruidDataSourceFactory.createDataSource(p);
       } catch (Exception e) {
    
        e.printStackTrace();
        }
   }

//  How to get the connection 
    public static Connection getConnection(){
    

        try {
    
            return dataSource.getConnection();
        } catch (SQLException e) {
    
            e.printStackTrace();
            return null;
        }
    }

    //  Release resources 
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
    
        if (connection != null && statement != null && resultSet != null){
    
            try {
    
                resultSet.close();
                statement.close();
//  Return connection 
                connection.close();
            } catch (SQLException throwables) {
    
                throwables.printStackTrace();
            }
        }
    }
}

package com.testpool;

import com.utils.DruidUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestDruid {
    
//  demand   Query salary in 3000~5000 Between   Of employees 

    public static void main(String[] args) throws SQLException {
    

// 1. Get the connection 
        Connection connection = DruidUtils.getConnection();

// 2. obtain statement object 
        Statement statement = connection.createStatement();

// 3. Execute the query 
        ResultSet resultSet = statement.executeQuery("select ename from employee where salary between 3000 and 5000");

// 4. Processing result set 
        while (resultSet.next()){
    
            String ename = resultSet.getString("ename");
            System.out.println(ename);
        }

// 5. Release resources 
        DruidUtils.close(connection,statement,resultSet);
    }
}

DBUtils Tool class

DBUtils brief introduction

  • Use JDBC We found too much redundant code , To simplify development , We choose to use DbUtils
  • Commons DbUtils yes Apache The organization provides a solution to DBC Open source tool class library for simple encapsulation , Using it can simplify JDBC Application development , At the same time, it will not affect the performance of the program
  • Usage mode :
    DBUtils Namely JDBC A simplified development kit for . Project import required commons-dbutils-1.6.jar.
     Insert picture description here

Dbutils Introduction to core functions

  1. QueryRunner Provided in pairs sql Statement operation API
  2. ResultSetHandler Interface , Used for definition select After the operation , How to encapsulate result sets
  3. DbUtils class , It's a tool class , It defines the methods of closing resources and transaction processing

Case related knowledge

The relationship between tables and classes

  • The whole table can be seen as a class
  • A row in a table , Corresponding to an instance of a class ( object )
  • A column in the table , Corresponding to a member attribute in the class
     Insert picture description here

JavaBean Components

1.JavaBean It's a class , It is usually used to encapsulate data in development , Has the following characteristics :;
1) Need to implement serialization interface ,Serializable( For the time being, you can omit )
2) Provide private fields :private type Variable name ;
3) Provide getter and setter
4) Provide Space parameter structure
2. establish Employee Objects and databases employee Table correspondence

package com.entity;


import java.util.Date;

/** * JavaBean class  *  Used to store data   Member variables are private   Provide get set  Provide empty parameters   implements Serializable  * * Employee class   It corresponds to employee surface  * * eid int PRIMARY KEY auto_increment, * ename VARCHAR(20), * age int, * sex VARCHAR(6), * salary DOUBLE, * empdate date */
public class Employee {
    
    
    private int eid ;
    
    private String ename ;
    
    private int age ;
    
    private String sex ;
    
    private double salary ;
    
    private Date empdate ;

    public Employee() {
    
    }

    public Employee(int eid, String ename, int age, String sex, double salary, Date empdate) {
    
        this.eid = eid;
        this.ename = ename;
        this.age = age;
        this.sex = sex;
        this.salary = salary;
        this.empdate = empdate;
    }

    public int getEid() {
    
        return eid;
    }

    public void setEid(int eid) {
    
        this.eid = eid;
    }

    public String getEname() {
    
        return ename;
    }

    public void setEname(String ename) {
    
        this.ename = ename;
    }

    public int getAge() {
    
        return age;
    }

    public void setAge(int age) {
    
        this.age = age;
    }

    public String getSex() {
    
        return sex;
    }

    public void setSex(String sex) {
    
        this.sex = sex;
    }

    public double getSalary() {
    
        return salary;
    }

    public void setSalary(double salary) {
    
        this.salary = salary;
    }

    public Date getEmpdate() {
    
        return empdate;
    }

    public void setEmpdate(Date empdate) {
    
        this.empdate = empdate;
    }

    @Override
    public String toString() {
    
        return "Employee{" +
                "eid=" + eid +
                ", ename='" + ename + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", salary=" + salary +
                ", empdate=" + empdate +
                '}';
    }
}

DBUtils complete CRUD

QueryRunner Core class

  • Construction method
    QueryRunner()
    QuerRunner(DataSource ds), Provide data sources ( Connection pool ),DBUtils Bottom layer automatic maintenance connection Connection
  • Common methods
update(Connection conn,String sql, Object ... params), Used to add table data 、 Delete 、 update operation 
query(Connection conn,String sql, ResultSetHandler<T> rsh ,Object ... params), Used to complete the query operation of table data 

QueryRunner The creation of

  • Manual mode
//  Mode one : Manual mode 
        QueryRunner qr = new QueryRunner() ;
  • Automatic mode
//  Mode two : Automatic mode   Provide database connection pool object  DBUtils Will automatically maintain the connection 
        QueryRunner qr2 = new QueryRunner(DruidUtils.getDataSource()) ;
  • Automatic mode requires an incoming connection pool object
//  obtain Druid Connection pool method 
    public static DataSource getDataSource(){
    
        return dataSource;
    }

QueryRunner Realize increase 、 Delete 、 Change operation

The core approach
update(Connection conn , String sql , Object… params)

Parameters explain
Connection conn Database connection object , Automatic mode creation QueryRunner Can not pass , Manual mode must pass
String sql In the form of a placeholder SQL, Use ? Place holder
Object… paramObject Type of Variable parameter , Used to set parameters on the placeholder
  • step
    1. establish QueryRunner( Manual or automatic )
    2. Placeholder method To write SQL
    3. Set the placeholder parameter
    4. perform
package com.testDBUtils;


import com.utils.DruidUtils;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;

/** *  Use QueryRunner  object   Complete the operation of adding, deleting and modifying  * update(Connection conn , String sql , Object... param) Method  */
public class DBUtilsDemo02 {
    

    @Test
    public void testInsert() throws SQLException {
    
// 1. establish QueryRunner  Manual mode creation 
        QueryRunner qr = new QueryRunner();

// 2. How to write a place holder  SQL
        String sql = "insert into employee values(?,?,?,?,?,?)" ;

// 3. Set the parameters of the placeholder 
        Object[] param = {
    null," Zhang wanwan " , 20 ," male ", 10000,"1990-12-26"};

// 4. perform update Method 
        Connection connection = DruidUtils.getConnection();
        int i = qr.update(connection , sql , param) ;

// 5. Release resources 
        DbUtils.close(connection);
    }


//  Modify the operating   Change the name to   The salary of Zhang million's employees is 15000
    @Test
    public void testUpdate() throws SQLException {
    

// 1. establish   Core class   Automatic mode   Delivery required   Database connection pool object 
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource()) ;

// 2. To write  SQL
        String sql = "update employee set salary = ? where ename = ?" ;

// 3. Set the parameters of the placeholder 
        Object[] param = {
    15000," Zhang wanwan "} ;

// 4. Perform modification operations   Automatic mode doesn't need to be passed in connection object 
        qr.update(sql,param) ;
    }

//  Delete operation   Delete id by 1 The record of 
    @Test
    public void testDelete() throws SQLException {
    

        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource()) ;

        String sql = "delete from employee where eid = ?" ;

//  If there is only one parameter , There is no need to create arrays 
        qr.update(sql,1);
    }
}


QueryRunner Implement query operation

ResultSetHandler Interface profile

  • ResultSetHandler It can be used to check out the ResultSet The result set is processed , Meet some business needs
  • QueryRunner The query method of
Method explain
query(String sql , handler , Object[] param) Automatic mode creation QueryRunner, Execute the query
query(Connection con, string sql , Object[] param) Manually create moss QueryRunner, Execute the query
  • query Methods return values that are generic , Specific return value types , Depending on how the result set is processed , change

ResultSetHandler Result set processing class

This example shows the use of ResultSetHandler Several common implementation classes of the interface realize the addition, deletion, modification and query of the database , Can greatly reduce the amount of code , The optimizer
Each implementation class represents a way to process the query result set

ResultSetHandler Implementation class explain
ArrayHandler Encapsulate the first record in the result set into a Object[] Array , Each element in the array is the value of each field in the record
ArrayListHandler Encapsulate every record in the result set into a Object[] Array , Encapsulate these arrays in List Collection
BeanListHandler Encapsulates the first record in the result set into a specified JavaBean in
BeanListHandler Encapsulate each record in the result set into a specified JavaBean in , And I'll put these JavaBean After packaging to List Collection
ColumnListHandler Sets the field value of the specified column in the result set to , Package into a List Collection
KeyedHandler Encapsulate each record in the result set into Map<String ,Object>, In the map Set as another Map Of value, the other one Map A collection of key Is the value of the specified field
MapHandler Encapsulate the first record in the result set into Map<String ,Object> Collection ,key That's the field name ,value Is the field value
MapListHandler Encapsulate every record in the result set into Map<String , Object> Collection ,key That's the field name ,value Is the field value , I'm putting these Map Package to List Collection
ScalaryHandler It is used to encapsulate single data . for example select count(*) from Table operations

ResultSetHandler Common implementation class testing

  • Create a test class , Yes ResultSetHandler Several common implementation classes of the interface are tested

    Inquire about id by 5 The record of , Encapsulate in an array
    Query all the data , Package to List Collection
    Inquire about Id by 5 The record of , Encapsulate to the specified JavaBean in
    Query salary greater than 3000 All employee information for , Package to JavaBean And then encapsulate it to List Collection
    The query name is Zhang million's employee information , Encapsulate the results to Map Collection
    Query the total salary of all employees

package com.testDBUtils;

import com.entity.Employee;
import com.sun.source.doctree.SeeTree;
import com.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.*;
import org.junit.Test;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DbUtilsDemo03 {
    

    /** * *  Inquire about id by 5 The record of , Encapsulate in an array  * ArrayHandler  Encapsulate the first data of the result set into an array  * */

    @Test
    public void testFindById() throws SQLException {
    

// 1. establish QueryRunner
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource()) ;

// 2. To write SQL
        String sql = "select * from employee where eid = ?" ;

// 3. Execute the query 
        Object[] query = qr.query(sql, new ArrayHandler(), 5);

// 4. Get array 
        System.out.println(Arrays.toString(query));

    }

    /** *  Inquire about id by 5 The record of , Encapsulate to a specified JavaBean in  * BeanHandler  Encapsulate the first data of the result set to JavaBean in  * */
    @Test
    public void testFindByIdJavaBean() throws SQLException {
    

        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

        String sql = "select * from employee where eid = ?" ;
        Employee employee = qr.query(sql, new BeanHandler<Employee>(Employee.class), 3);

        System.out.println(employee);
    }

    /** *  Query salary greater than 3000 All employee information for , Package to JavaBean And then encapsulate it to List Collection  * BeanListHandler  Encapsulate every record and data of the result set into JavaBean in   then JavaBean  Put it in List Collection  * */
   @Test
    public void testFindBySalary() throws SQLException {
    

        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource()) ;

        String sql = "select * from employee where salary > ?" ;

        List<Employee> list = qr.query(sql, new BeanListHandler<Employee>(Employee.class), 3000);

        for (Employee employee: list){
    
            System.out.println(employee);
        }
    }

    /** *  The query name is Zhang million's employee information , Encapsulate the results to Map Collection  * MapHandler  Encapsulate the first record of the result set to Map<String , Object> * key The corresponding is the column name  value  It corresponds to the value of the column  * */
    @Test
    public void testFindByName() throws SQLException {
    

        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource()) ;

        String sql = "select * from employee where ename = ?" ;

        Map<String, Object> map = qr.query(sql, new MapHandler(), " Zhang wanwan ");

        Set<Map.Entry<String , Object>> entries = map.entrySet();

        for (Map.Entry<String , Object> entry : entries){
    

//  Print the results 
            System.out.println(entry.getKey() + "=" + entry.getValue());
        }
    }

    /** *  Query the total salary of all employees  * ScalarHandler  Used to encapsulate individual data  * */
    @Test
    public void testGetSum() throws SQLException {
    

        QueryRunner  qr = new QueryRunner(DruidUtils.getDataSource()) ;

        String sql = "select sum(salary) from employee" ;

        double sum = (double) qr.query(sql, new ScalarHandler<>());

        System.out.println(" The total salary of employees : " + sum);
    }
}

establish BeanHandler You need to pass a parameter , The parameter is JavaBean Class class File object
Employee.class Create... By reflection Employee Object encapsulates the result set into an object And back to

Database batch processing

What is batch processing

  • The batch (batch) Operating the database
 Batch processing refers to the execution of multiple SQL sentence , Batch processing is much more efficient than once at a time 
 When you add a lot of data to a database , Batch processing is needed 
  • give an example : The delivery man's job :
  • When batch processing is not used , The deliveryman can only deliver one piece of goods to the merchant at a time
  • Using batch processing is to send the deliveryman all the goods to be transported , They all take the car to the distribution office and send it to customers

Implement batch processing

Statement and PreparedStatement Both support batch operations
PreparedStatement The batch method of
1) The method to be used

Method explain
void addBatch() Will be given SQL Add the command to this Statement In the current command list of the object .
By calling a method executeBatch You can batch execute the commands in this list
int[] executeBatch() Each time a batch of commands are submitted, they are executed in the database , If all the commands are executed successfully ,
So return an array , This array describes the number of rows affected by each command

2)mysql Batch processing is turned off by default , So you need to add a parameter to open mysql Database batch processing , stay url Add


package com.testbatch;

import com.utils.DruidUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class BatchInsert {
    
// Use batch processing to add  10000  Data 
    public static void main(String[] args) throws SQLException {
    

//1. Get the connection 
        Connection connection = DruidUtils.getConnection() ;

// 2. Get preprocessing object 
        PreparedStatement ps = connection.prepareStatement(" insert into testBatch(uname) values(?)");

// 3. Perform a batch insert operation 
        for (int i= 0 ; i < 10000 ; i++){
    
            ps.setString(1," cockroach " + i );

//  take SqL Add to batch list 
            ps.addBatch();
        }

//  Add time stamp   Test execution efficiency 
        long start = System.currentTimeMillis();

// 4. Unified execution   Bulk insert operation 
        ps.executeBatch();

        long end = System.currentTimeMillis();

        System.out.println(" Insert 10000 Pieces of data need to use : " + (end - start) + " millisecond ");
// 5. Close the connection 
        DruidUtils.close(connection , ps);
    }
}

MySQL Metadata

What is metadata

  • Data other than tables is metadata , It can be divided into three categories :

Query result information :Update or Delete sentence Number of records affected
Database and table information : Contains the database as well as Data sheet Structure information of
MySQL server information : Contains the current state of the database server , Version number, etc

Common commands

--- Introduction to metadata related commands 
1. View the current status of the server 

show status;

2. see MySQL Version information for 

select version();

3. Look up the details in the table 

show columns from  Table name ;

4. Display detailed index information of table data 

show index from  Table name ;

5. List all databases 

show databases ;

6. Displays all tables in the current database 

show tables;

7. Get the current database name 

select database();

Use JDBC Fetch metadata

adopt JDBC You can also get metadata , For example, the relevant information of the database , Or when we use a program to query an unfamiliar table , We can get metadata information by , Understand how many fields are in the table , Name of field and Type of field

Common class introduction

JDBC Metadata classes described in

metadata class effect
DatabaseMetaDate Describe the metadata object of the database
ResultSetMetaData Metadata object that describes the result set
  • Methods to get metadata objects :getMetaData()

connection Connection object , call getMetaData() Method , What you get is DatabaseMetaData Database metadata object
PreparedStatement Preprocessing object calls getMetaData() , What you get is ResultSetMetaData, Result set metadata object

  • DatabaseMetaData The common method of
Method statement
getURL(): Get the URL
getUserName() : Get the user name of the current database
getDatabaseProductName(): Get the product name of the database
getDatabaseProductVersion(): Get the version number of the database
getDriverName(): Returns the name of the driver
isReadOnly(): Determine whether the database is only allowed to be read-only true Read only
  • ResultSetMetaData The common method of
Method statement
getColumnCount(): How many columns are there in the current result set
getColumnName(int i): Gets the column name of the specified column number , The parameter is an integer from 1 Start
getColumnTypeName(int i): Gets the type of the specified column number , The parameter is an integer from 1 Start
package com.testmetadata;

import com.utils.DruidUtils;
import org.junit.Test;

import java.sql.*;
import java.util.Properties;

public class TestMetaData {
    
// 1. Get the metadata information related to the database   Use DatabaseMetaData
    @Test
    public void testDataBaseMetaData() throws SQLException {
    

// 1. Get database connection object  connection
        Connection connection = DruidUtils.getConnection();

// 2. Get metadata information related to the representative database 
        DatabaseMetaData metaData = connection.getMetaData();

        String url = metaData.getURL() ;
        System.out.println(" database URL:" + url);

        String userName = metaData.getUserName();
        System.out.println(" The current user : " + userName);

        String databaseProductName = metaData.getDatabaseProductName();
        System.out.println(" Database product name : " + databaseProductName);

        String databaseProductVersion = metaData.getDatabaseProductVersion();
        System.out.println(" Database version : " + databaseProductVersion);

        String driverName = metaData.getDriverName();
        System.out.println(" Database driver name : " +driverName);

        boolean readOnly = metaData.isReadOnly();
        System.out.println(" Whether the database is read-only : " + readOnly);

        connection.close();

    }

//  Get the metadata information in the result set 

    @Test
    public void restResultSetMetaData() throws SQLException {
    
// 1. Get the connection 
        Connection connection = DruidUtils.getConnection();

// 2. Get preprocessing object 
        PreparedStatement ps = connection.prepareStatement("select * from employee") ;
        ResultSet resultSet = ps.executeQuery();

// 3. Get the result set metadata object 
        ResultSetMetaData metaData = ps.getMetaData();

//  Get the current result set   How many columns are there in total 
        int count = metaData.getColumnCount();
        System.out.println(" In the current result set : " + count + " Column ");



        for (int i = 1 ; i <= count ; i++){
    
            //  Get the name of the specified column number   and   type , The parameter is an integer 
            String catalogName = metaData.getColumnName(i);
            System.out.println(" Name : " +catalogName);

            String columnTypeName = metaData.getColumnTypeName(i);
            System.out.println(" type : " + columnTypeName);
        }


//  Release resources 
        DruidUtils.close(connection,ps,resultSet);

    }
}

原网站

版权声明
本文为[Qing]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230756008135.html