1. Introduction to JDBC
2 jdbc usage
Driver package: link: https://pan.baidu.com/s/1JHNtgBS8VwVvAX41RsMbTA
Extraction code: ehuk
import com.mysql.jdbc.PreparedStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; public class TestJdbc { public static void main(String[] args) throws ClassNotFoundException, SQLException, SQLException { /* 1: Register driver After mysql5.0, there is no need to register the driver, and the driver has been brought with it But we can write forward compatibility */ /*The reason why the driver can be registered: public class Driver extends NonRegisteringDriver implements java.sql.Driver { public Driver() throws SQLException {} static { try { DriverManager.registerDriver(new Driver()); } catch (SQLException var1) { throw new RuntimeException("Can't register driver!");}}} */ Class.forName("com.mysql.jdbc.Driver"); /* 2:Get database connection object DriverManger Class function: 1)Manage and register drivers 2) Create a connection to the database <1>:Connection getConnection (String url, String user, String password) through The connection object of the database is obtained through the connection string, user name and password <2>:Connection getConnection (String url, Properties info->Write your own configuration document The connection object is obtained through the connection string and attribute object Writing configuration file format: url = "jdbc:mysql://localhost:3306/ Connection database name "; <3>:Solution to garbled code (specify database encoding method): jdbc:mysql://localhost:3306/database characterEncoding=utf8 <4>:Short url premise: it must be a local server and the port number is 3306 Abbreviation: jdbc:mysql: / / / database name */ Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/nanzi", "root", "root"); /* 3 :Gets the object that executes the sql statement Connection Class: 1)Gets the object that executes the sql statement <1>:Get the ordinary performer object: Statement createStatement(); Statement Object is not recommended because of unsafe sql injection sql Injection problem: it is to make database errors through special splicing sql statements Example: select * from table name where name = 'Zhang San' and pass ='123 'or' a '='a'; In this way, the data in the database will be confused and recognized <2>:Get the precompiled performer object: PreparedStatement prepareStatement(String sql); Precompiled object solves the problem of sql injection. Precompile first through question marks as placeholders, and then through precompiling The translation object assigns a value to the placeholder Assignment method: PreparedStatement object. setXxx(? Sequence number, value - > pay attention to string and number); Note: the assignment starts from 1, not 0 2)Transaction processing (sequence) Start transaction: setAutoCommit(boolean autoCommit); If the parameter is false, the transaction is started. Commit transaction: commit(); Rollback transaction: rollback(); Special note: the transaction operation should be implemented in the service layer, and the dao layer generally only does simple database logic */ PreparedStatement preparedStatement = (PreparedStatement) connection.prepareStatement("select * from nanfengmessage where name=? and pass=? ?"); preparedStatement.setString(1, "name"); preparedStatement.setInt(2, 123); /*4: Execute the sql statement and receive the returned object: 1)Execute dml: modify, etc int i = preparedStatement.executeUpdate(); The return value indicates the number of affected rows: it is generally used to judge the execution result of sql statements. If it is greater than 0, it indicates execution The line is successful, otherwise the execution fails 2)Execute dql: query ResultSet resultSet = preparedStatement.executeQuery(); ResultSet Execution result encapsulation class: Common methods: next() boolean; Used to obtain the next set of data in the query result data table (equivalent to The table contains an arrow pointing to the next row each time. If there is data Returns true, no number false (similar to iterator), and traverses common getXXX("Column name "") XXX type; specify column name to get data results getXXX((column number) XXX type; formulate method column number to obtain data results */ ResultSet resultSet = preparedStatement.executeQuery(); //Traverse the results while (((ResultSet) resultSet).next()) { String name = resultSet.getString("name"); System.out.println(name); //Specific treatment } /*5: Finally, release resources: */ connection.close(); preparedStatement.close(); resultSet.close(); } }
Comparison table of data acquisition:
Extraction of tool classes:
public class JDBCUtils { private static String driverClass; private static String databaseName; private static String databasePass; private static String databaseURL; //Initialize data through static code blocks static { //Get the bytecode file of the current class, and get the class loader through the bytecode file ClassLoader classLoader = JDBCUtils.class.getClassLoader(); //Load the specified file through the classloader to obtain the input stream object (the file path must be in the src directory or absolute path) InputStream resourceAsStream = classLoader.getResourceAsStream("db.properties"); //Create the Properties collection and load the data in the stream through the load method Properties properties = new Properties(); try { properties.load(resourceAsStream); //Get the data in the file (according to the key name in the file, don't write it wrong) databaseURL = properties.getProperty("URL"); driverClass = properties.getProperty("driverClass"); databaseName = properties.getProperty("name"); databasePass = properties.getProperty("password"); //Register driver Class.forName(driverClass); } catch (ClassNotFoundException | IOException e) { e.printStackTrace(); } } private JDBCUtils() { } public static Connection getConnection() throws SQLException { Connection connection = DriverManager.getConnection(databaseURL, databaseName, databasePass); return connection; } public static void close(Connection connection, Statement statement) { //This parameter adopts statement. Preparedstatement is a subclass of statement (polymorphic) //Make non empty judgment if (statement != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(Connection connection, Statement statement, ResultSet resultSet) { if (resultSet != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } close(connection, statement); } }
Several configuration files for database connection:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///mybatismussary
username=root
password=rootÂ
Database connection pool
3 c3p0 database connection pool
Use steps:
(1) Import jar packages (three)
<1> c3p0-0.9.5.2.jar
<2> Mchange-commons-java-0.2.12.jar (c3p0 dependent package)
<3> Database driver jar package: mysql-connector-java-5.1.37-bin.jar
Link: https://pan.baidu.com/s/1ZNItHGXaTT6to2RoJkr7_Q
Extraction code: fjy4
(2) Define the configuration file: Name: c3p0.properties or c3p0-config.xml (must be named like this) path: directly put the file in the src directory.
C3p0-config.xml (you can copy and paste directly)
c3p0.properties example (copy modification available):
c3p0.JDBC.url=jdbc:mysql://localhost:3306/ Library name? characterEncoding=utf8 c3p0.DriverClass=com.mysql.jdbc.Driver c3p0.user=root c3p0.pwd=root c3p0.acquireIncrement=3 c3p0.idleConnectionTestPeriod=60 c3p0.initialPoolSize=10 c3p0.maxIdleTime=60 c3p0.maxPoolSize=20 c3p0.maxStatements=100 c3p0.minPoolSize=5
import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; public class C3p0PoolUtils { private static DataSource ds; static { //Get database connection pool object ds = new ComboPooledDataSource(); } private C3p0PoolUtils() { } public static Connection getConnection() { Connection connection = null; try { connection = ds.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return connection; } }
four Druid: database connection pool implementation technology, provided by Alibaba
Extraction code: sibk
(4) Get database connection pool object: get DruidDataSourceFactory through the factory
(5) Get connection: getConnection
import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.IOException; 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 DruidJDBCUtils { private static DataSource dataSource; //Load profile static { Properties properties = new Properties(); InputStream resourceAsStream = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties"); try { properties.load(resourceAsStream); //Get database connection pool object dataSource = DruidDataSourceFactory.createDataSource(properties); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } private DruidJDBCUtils() { } public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } public static DataSource getDataSource() throws SQLException { return dataSource; } public static void close(Connection connection, Statement statement) { if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(Connection connection, Statement statement, ResultSet resultSet) { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } close(connection, statement); } }
Test code:
import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Properties; public class NanFengDruid { public static void main(String[] args) throws Exception { //Load profile Properties properties = new Properties(); properties.load(NanFengDruid.class.getClassLoader().getResourceAsStream("druid.properties")); //Get connection object factory DataSource dataSource = DruidDataSourceFactory.createDataSource(properties); //Get database connection object Connection connection = dataSource.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("select * from nanfengmessage"); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { System.out.println(resultSet.getInt("id") + "\t" + resultSet.getString("name") + "\t" + resultSet.getString("pass")); } resultSet.close(); preparedStatement.close(); connection.close(); } }
In addition, Spring also provides a database connection pool, which will not be explained separately here. It will be discussed in the following overview of the Spring family!
5. User defined database connection pool (brief description)
import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class NanFengCreatDataSourcePool { //Ensure thread safety private static List<Connection> list = Collections.synchronizedList(new ArrayList<Connection>()); static { for (int i = 0; i < 10; i++) { try { Connection connection = JDBCUtils.getConnection(); list.add(connection); } catch (SQLException e) { e.printStackTrace(); } } } public int getSize() { return list.size(); } public static Connection getConnection() { if (list.size() > 0) { Connection connection = list.get(0); list.remove(0); return connection; } else { throw new RuntimeException("The connection object is gone"); } } public static void clos(){ } }