JDBC + C3P0 + DBCP use substantially

@

1 Overview

This article says the basics of using JDBC, including the Statement, PreparedStatement, JDBC connection, Mysql create user-created data table, C3P0 connection and configuration, DBCP connection and configuration.

2.mysql processing

JDBC is used here as Mysql DBMS, please install Mysql, not installed , please click here to download , install tutorial here , Mysql 8.0.17 version used by the author.

(1) New User

Just create a new user, such as the new author here is aa, the password is aa123bb.

create user 'aa'@'localhost' identified by 'aa123bb'

(2) establishing a data table

Establish a data table and database testing.

create database db;
use db;

create table db
(
    id int PRIMARY key,
    name char(20)
);

(3) user rights

For just the new user authorization:

grant select,update,delete,insert on db.* to 'aa'@'localhost';

2.JDBC

(1) jar 包

8.0.17 version here

Various versions of the download here

(2) is connected

First registration drive, the drive requires a url, user name and password, user name and password is the last step to create a good, url contains the name of the ip address, port, and database.

private static final boolean mysqlVersionGreaterThen8 = true;
private static final String driver = "com.mysql" + (mysqlVersionGreaterThen8 ? ".cj" : "") + ".jdbc.Driver";
private static final String ip = "127.0.0.1";
private static final String port = "3306";
private static String databaseName = "db";
private static String url;
private static String username = "aa";
private static String password = "k041400r";
private static Connection connection = null;

public static Connection getConnection() {
    try {
        url = "jdbc:mysql://" + ip + ":" + port + "/" + databaseName;
        Class.forName(driver);
        return connection = DriverManager.getConnection(url, username, password);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

Here we must note the following older versions of the driver mysql called com.mysql.jdbc.Driver, the new version is called com.mysql.cj.jdbc.Driver there is the url of the format:

jdbc:mysql://ip:port/database

(3)Statement

After obtaining a database connection, use createStatement method to create a Statement

  • For select, using Statement of executeQuery (sql), returns ResultSet
  • For update, delete, insert, use the Statement of executeUpdate (sql)

Sql sql statement which is to be executed, a String.

public void useStatement() {
    try {
        useStatementInsert();
        useStatementSelect();
        useStatementUpdate();
        useStatementSelect();
        useStatementDelete();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

public void useStatementInsert() throws SQLException {
    String sql = "insert into db(id,name) values(1,'23')";
    Statement statement = connection.createStatement();
    statement.executeUpdate(sql);
}

public void useStatementDelete() throws SQLException {
    String sql = "delete from db";
    Statement statement = connection.createStatement();
    statement.executeUpdate(sql);
}

public void useStatementSelect() throws SQLException {
    String sql = "select * from db";
    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery(sql);
    ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
    int count = resultSetMetaData.getColumnCount();
    while (resultSet.next()) {
        for (int i = 1; i <= count; ++i) {
            System.out.println(resultSet.getObject(i));
        }
    }
}

public void useStatementUpdate() throws SQLException {
    Statement statement = connection.createStatement();
    String sql = "update db set id = 3,name = '555' where id = 1";
    statement.executeUpdate(sql);
}

Of the getMetaData ResultSet used herein, the result set can obtain various types of information, including the type of field, the number, and the like.

(4)PreparedStatement

PreparedStatement and Statement using essentially the same. When the call to create the Connection of prepareStatement (sql), and then

  • For select, using executeQuery (), returns a ResultSet
  • For update, delete, insert use executeUpdate ().
public void usePrepareStatement() {
    try {
        usePrepareStatementInsert();
        usePrepareStatementSelect();
        usePrepareStatementUpdate();
        usePrepareStatementSelect();
        usePrepareStatementDelete();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

public void usePrepareStatementInsert() throws SQLException {
    String sql = "insert into db(id,name) values(1,'23')";
    PreparedStatement preparedStatement = connection.prepareStatement(sql);
    preparedStatement.executeUpdate();
}

public void usePrepareStatementDelete() throws SQLException {
    String sql = "delete from db";
    PreparedStatement preparedStatement = connection.prepareStatement(sql);
    preparedStatement.executeUpdate();
}

public void usePrepareStatementSelect() throws SQLException {
    String sql = "select * from db";
    PreparedStatement preparedStatement = connection.prepareStatement(sql);
    ResultSet resultSet = preparedStatement.executeQuery();
    ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
    int count = resultSetMetaData.getColumnCount();
    while (resultSet.next()) {
        for (int i = 1; i <= count; ++i)
            System.out.println(resultSet.getObject(i));
    }
}

public void usePrepareStatementUpdate() throws SQLException {
    String sql = "update db set id = 3,name = '555' where id = 1";
    PreparedStatement preparedStatement = connection.prepareStatement(sql);
    preparedStatement.executeUpdate();
}

(5) Transaction

Connection has a setAutoCommit () method, set it to false to turn off the automatic submission, all statements ready, single-use commit () submitted to.
Implement the rollback can match SavePoint use.

3.C3P0

(1) jar 包

Two:

(2) Profile

Create a file called src c3p0.properties under:

c3p0.driverClass=com.mysql.cj.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://127.0.0.1:3306/db
c3p0.user=aa
c3p0.password=aa123bb

Here you can change according to their needs.

(3) Tools

import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;

public class DbUtil
{
    private static ComboPooledDataSource C3P0dataSource = new ComboPooledDataSource("c3p0.properties");
    public static void releaseConnection(Connection connection)
    {
        try
        {
            if(connection != null)
                connection.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static Connection getC3P0Connection()
    {
        try
        {
            return C3P0dataSource.getConnection();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
}

4.DBCP

(1) jar 包

Three:

(2) Profile

src under the new dbcp.properties:

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/db
username=aa
password=k041400r
initialSize=10
maxActive=50
maxIdle=15
minIdle=10
maxWait=60000
connectionProperties=useUnicode=true;characterEncoding=utf8
defaultAutoCommit=true

Are driven, url, user name, password, initializing the number of connections, the maximum number of connections, the maximum number of idle connections, the minimum number of idle connections, the actual maximum latency, connection properties (here set encoding), automatic submission.

(3) Tools

import org.apache.commons.dbcp2.BasicDataSourceFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;
import javax.sql.DataSource;

public class DbUtil {
    private static DataSource DBCPdataSource;
    static {
        try {
            InputStream inputStream = DbUtil.class.getClassLoader().getResourceAsStream("dbcp.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            DBCPdataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getDBCPConnection() {
        try {
            return DBCPdataSource.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void releaseConnection(Connection connection) {
        try {
            if (connection != null)
                connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

A properties file first, and then load method using Properties loaded into a Properties object, and finally to BasicDataSourceFactory process.

5. Source

The package comprising a jar, profile, sql test code file.

Guess you like

Origin www.cnblogs.com/Blueeeeeeee/p/11894945.html