jdbc transaction data source

Posted by arcanechaos on Thu, 05 Dec 2019 18:54:24 +0100

Affairs:

Why do you want to open a transaction? In the program, it's not just compiled, but the same as the logical line.

Transactions can help us to execute logic better


Data source:

Database connection optimization helps us link databases faster

If the data source has a database pool, you can take it directly from the database pool

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

public class T1 {
    /**
     * Common connection objects
     */
    private static T1 ourInstance = new T1();
    private DataSource dataSource = null;//Request a data source interface is empty

    public static T1 getInstance() {
        return ourInstance;
    }

    private T1() {//Because here's the constructor. Whenever you create an object, you call the constructor first
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        try {
            comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
            comboPooledDataSource.setJdbcUrl("jdbc:mysql://47.101.201.210/Test?useSSL=FALSE&serverTimezone=UTC");
            comboPooledDataSource.setUser("root");
            comboPooledDataSource.setPassword("Sb1996350.");
            comboPooledDataSource.setMaxPoolSize(3);//maximum connection
            comboPooledDataSource.setMinPoolSize(1);//Minimum connections
            dataSource = comboPooledDataSource;
            Connection connection = dataSource.getConnection();//The getConnection method in dataSource is needed to return the connection object
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Connection getdataSource() throws Exception {
        return dataSource.getConnection();
    }

    public static void main(String[] args) throws Exception {
        Connection connection = new T1().getdataSource();
        connection.setAutoCommit(false);//Why do I need to open a transaction when I open a transaction? If I have not compiled it in the code, I will be successful. If I have logic, I will be successful
        connection.commit();//Submission of affairs
        //There is also an advantage of opening a transaction. The transaction has an exclusive lock. When you modify the data, you can ensure that the data is unique
        connection.close();
    }
}

It's loaded database connection

Topics: Java Database SQL MySQL