The use of Java JDBC

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/liu_Yudong/article/details/97763602

JDBC Resource Kit
links: https://pan.baidu.com/s/1JaZ3gn7DDVVhF0XcEfBtsQ
extraction code: 858d

JDBC database operation process

  1. The Class.forName () to load the database connection driver.
  2. The DriverManager.getConnection () Gets the data connection object.
  3. Get the session object based on a SQL statement, the session object type generally used PreparedStatement
  4. Execute SQL result set
  5. Result set is closed, close the session, the connection is closed

Package function

public class SqlUtils {
    private static String driver = "com.mysql.jdbc.Driver";
    private static String url = "";
    private static String username = "";
    private static String password = "";

    static {
        //加载驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //只产生一个连接
    public static Connection getConnection() throws SQLException {
        System.out.println("连接数据库...");
        return DriverManager.getConnection(url, username, password);
    }

    public static void release(Connection connection, Statement statement, ResultSet resultSet) {

        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Test Case

public class test {
    public static void main(String[] args) throws SQLException {
        //加载驱动,创建连接
        Connection connection = SqlUtils.getConnection();
        //SQL语句
        String insert = "INSERT INTO `user` (id,username,password) VALUE (?,?,?);";
        String select = "SELECT * FROM `user`;";
        //将事务设置为手动提交
        connection.setAutoCommit(false);
        PreparedStatement statement1;
        PreparedStatement statement2;
        try{
            //根据sql语句,得到预编译语句对象
            statement1 = connection.prepareStatement(insert);
            statement2 = connection.prepareStatement(select);

            for(int i=1;i<=10;i++){
                //按占位符设置参数值
                statement1.setInt(1,i);
                statement1.setString(2,"user_"+i);
                statement1.setString(3,"password"+i);
                //放入批处理队列
                statement1.addBatch();
            }
            //执行插入语句,批量插入,事务
            statement1.executeBatch();

            //执行查询语句,得到结果集
            ResultSet result = statement2.executeQuery();
            //遍历、打印结果
            while (result.next()){
                System.out.println("username:"+result.getObject("username")+";password:"+result.getObject("password"));
            }
            //提交事务
            connection.commit();

            //关闭连接,释放资源
            SqlUtils.release(connection,statement1,result);
            SqlUtils.release(connection,statement2,result);

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

PreparedStatement Statement object and the object

PreparedStatement inherits Statement, PreparedStatement contains a compiled SQL statement that executes faster than Statement. Statement frequently compiled SQL. PreparedStatement can be precompiled SQL to improve efficiency, PreparedStatement object is precompiled SQL stored.
In JDBC, no time to use the Statement, because:

  1. Readability and maintainability of the code, Statement requires continuous stitching
  2. PreparedStatement better performance, caching mechanism
  3. PreparedStatement more high security, Statement sql easily be injected, by delimiter '++', never write the equation can be entered into the database without a password, PreparedStatement incoming content will not happen any sql statement and matching relationship

Database connection pooling mechanism

Preparation: the establishment of a database buffer pool

  1. Acquiring or creating a connection from the connection pool
  2. End use, the connection returned to the pool
  3. When the system is off, disconnect all connections and release resources
  4. Total able to handle invalid connection, connection pool limit and not more than a certain value is not less than

The minimum number of connections: connections connection pool remains the
maximum number of connections: connection pool can apply the maximum number of connections, if exceeded, entering the latter data connection request queue
connection pool has maintained a number less than the minimum number of connections, when when an insufficient number, the database will create a new connection until the maximum number of connections, then the database will wait

Common open source connection pool: DBCP, C3P0, Druid

Guess you like

Origin blog.csdn.net/liu_Yudong/article/details/97763602