Java Database Connectivity -JDBC (JDBC Detailed, JDBC control transactions, C3P0 connection pool, Druid connection pool, Spring JDBC-JDBC Template)

Java Database Connectivity -JDBC (JDBC Detailed, JDBC control transactions, C3P0 connection pool, Druid connection pool, Spring JDBC-JDBC Template)

<<<<< CSDN layout and display pictures have a little problem, so look beautiful into full Java Database Connectivity -JDBC (JDBC Detailed, JDBC control transactions, C3P0 connection pool, Druid connection pool, the Spring JDBC-JDBC Template) >>> >>

1、JDBC

①JDBC concept and nature

JDBC (Java DataBase Connectivity, java Database Connectivity) is a Java API to execute SQL statements used, can provide unified access to multiple relational database that consists of a set written in Java classes and interfaces. JDBC provides a benchmark that allow you to build more advanced tools and interfaces that enable database developers to write database applications.
JDBC is in fact the essence of the official rules (Sun Company) defined by a set of operating all relational databases, namely the interface. Each database vendor to achieve this excuse, to provide database driver jar package, we can use this set of interfaces (JDBC) programming, the code execution is the real driver jar package implementation class.

② Download

Method 1: Enter https://dev.mysql.com/downloads/connector/j/ After selecting Platform Independent, click to download; or into https://mvnrepository.com/ select the corresponding version can also be downloaded
way: into the MySQL official website >>> click DOWNLOADS >>> click Community >>> click MySQL Connectors >>> click Connector / J >>> select Platform Independent >>> download it

MySQL Connector / J 8.0 the previous version of the class name is com.mysql.jdbc.Driver
MySQL Connector / J 8.0 start class name changed to com.mysql.cj.jdbc.Driver

③ preliminary tests used (following the example just to give first-time entry of about JDBC)

Step:
1. Import Driver jar package
in a New Project Intellij IDEA Module1 after a new, a new directory in the lib Module, secondary to "mysql-connector-java-5.1.37 -bin.jar" copied into, and then right right lib directory aS Library the Add
2. Register drive
a new Package, then create a new Class, the following code is written in the main function:
the Class.forName ( "com.mysql.jdbc.Driver");
more codes registered driver, Note that to deal with abnormal
3. Access database connection object connection
connection connection the DriverManager.getConnection = ( "JDBC: MySQL: // localhost: 3306 / HH", "the root", "the root");
the code above, HH database name, the first root for MySQL login account, the second for MySQL root login account password
4. define SQL
String SQL = "UPDATE employees the SET Achievement = 100";
the code above, I would employees of my computer hh database the achievement of modified fields 100
5. obtain the object to execute SQL statements the statement
the statement statement Connection.createStatement = ();
6. the SQL execution, receiving returns fruit
Statement.executeUpdate I = int (SQL);
7. The processing result
System.out.println (I);
8. The release resources
Statement.close ();
Connection.close ();
9. The results of
the database data modified successfully
complete code follows Figure:

④JDBC each class Detailed

DriverManager-JDBC driver manager objects
function
1, registered drivers: tell the program which database driver jar using
static void registerDriver (Driver driver) to register with the DriverManager given driver
Class.forName ( "com.mysql.jdbc.Driver") ;
in com.mysql.jdbc.Driver source can be seen in the following paragraph static block of code:
static {
the try {
DriverManager.registerDriver (new new Driver ());
} the catch (SQLException var1) {
the throw a RuntimeException new new ( "can Not Register ! driver ");
}
}
Note: MySQL5 drive jar package after the META-INF / services / java.sql.Driver code register will automatically help you drive, so you can omit Class.forName (" com.mysql. jdbc.Driver ")
2, database connection
static connection getConnection (String url, String user, String password) Attempts to establish a connection to the given database URL
url: url database (syntax: jdbc: mysql: // IP address or domain name: port number / name of the database) If the connection is a local MySQL server and the port is 3306, the url can be shortened jdbc: mysql: /// database name
Connection - database connection object
function
1, to obtain the object execute the SQL
statement createStatement () Creates a statement object for sending SQL statements to the database
PreparedStatement prepareStatement (String sql) Creates a PreparedStatement object for sending parameterized SQL statements to the database
2, management transaction
open transaction: void setAutoCommit (boolean autoCommit) autoCommit - true to enable auto-commit mode; false to disable auto-commit mode
commits the transaction: void commit () makes all since the previous commit / rollback changes become lasting change, this Connection object and releases any database locks currently held
rollback the transaction: void rollback () to cancel all changes made in the current transaction and releases any database locks currently held by this Connection object
Statement- executing a static SQL statement and returns it The results generated object
execution method SQL
boolean execute (String sql) Executes the given SQL statement, which may return a plurality of result, if the first result is a ResultSet object, the return true; if its count is updated or there are no the results, false is returned
int executeUpdate (String sql) may execute SQL statements for the DML statements (INSERT, UPDATE, or DELETE), there does not return any SQL statement (DDL statements)
(1) for the SQL Data Manipulation Language (DML) statements, the return line count (2) for DDL such statement, return 0 (return value based DML statement is executed successfully, the return value> 0 successful)
the ResultSet the executeQuery (String SQL) execution of a given SQL statement, usually static DQL ( SELECT) statement that returns a single ResultSet object

The examples of "③ initial testing using the" improved look, the code is as follows:

Project drawings and execution results is as follows:

ResultSet- result set object, the results of the query package
boolean next (): move the cursor from the current position to the next row direction; if the new current line is valid, returns true; If the next line is not present, false is returned. While loop to acquire data with
getXxx (int columnIndex): Get the result of each column (column Xxx representing each data type); the method is of type int received parameter representative to obtain the number of the column, the column numbers are from left to right starts counting
getXxx (String columnLabel): Get the result of each column (column Xxx representing each data type); the method receives as parameters of type String, represents the name column in the database
using the above two ways getXxx int parameter or parameters String can achieve the same effect
, for example, the example of FIG query:

Query results are as shown below:

PreparedStatement- pre-compiled object in SQL statements
SQL injection: submitted by the SQL commands inserted into a Web form or enter a domain name or page request query string, and ultimately to deceive the server to execute malicious SQL commands
such as: is the use of AND and OR rules of operation, resulting script logic error back
then I use 'xxx' or 'a' = 'a' to do the user name and password, then the query becomes:
the SELECT * the FROM adminbate the WHERE the user = 'xxx' the AND password = 'xxx' OR 'a' = 'a' >>> WHERE condition becomes true
above SQL injection problems can be solved by PreparedStatement object using pre-compiled SQL, i.e. parameters? rather than as a placeholder by splicing
Getting SQL statement object and the above examples written in different, by
creating a PreparedStatement object Connection method PreparedStatement prepareStatement (String sql) sent parameterized SQL statements to the database
void setXxx (int parameterIndex, Xxx x ) will be specified parameter for a given input stream. Xxx represents type;? Denotes where parameterIndex position, counting from 1; X represents the value of the parameter?
PreparedStatement can pass after sql, before executing the statement, assigned to the parameters, to avoid the result of normal stitching string sql statement brought security issues, and prepare and execute sql sql statements which are completed in two, but also improve the efficiency of execution of sentence such as single quotes will give you an escape plus, add a slash. The above sql statement execution is so in the database
SELECT * FROM adminbate WHERE user = ' xxx' AND password = '' xxx 'OR' a '=' a ''
development is performed using a PreparedStatement CRUD operations, since 1, 2 safe, efficient

⑤JDBC control transactions

Transaction database (abbreviation: transaction) during the execution of a logical unit is a database management system, the operation consists of a finite sequence database; plurality of steps performed together at the same time either succeed or fail concurrently
Connection Management Object operation
a start transaction void setAutoCommit (boolean autoCommit) connected to this auto-commit mode to the given state, autoCommit - true to enable auto-commit mode; false to disable auto-commit mode (begin transaction before executing SQL statements)
2, commit the transaction void commit () makes all changes made since the previous commit / rollback permanent and releases any database locks currently held by this Connection object (when all transactions are submitted executing the SQL transaction)
3, roll back the transaction void rollback () to cancel all changes made in the current transaction and releases any database locks currently held by this Connection object (you can roll back the transaction in the catch)
JDBC transactions case (core code):

When the caught exception, try to capture a relatively large range, such as the example in FIG Exception, as had transaction rollback in the event of any abnormality

⑥ database connection pool

Database connection pool
database connection pool is responsible for the distribution, management and release of database connections, which allows an application to reuse an existing database connection, rather than re-create a; release the database connection idle for more than the maximum idle time to avoid because there is no release database connection caused the database connection omissions. This technology can significantly improve the performance of database operations.
Interface javax.sql DataSource (note the lower javax package; DataSource interface is implemented by the driver vendor)
acquires the connection
Connection getConnection () tries to establish a data source DataSource object represented by this connection. Returns: the connection to the data source
to return the connection
if the connection object Connection is to obtain from the connection pool, then call Connection.close () method will not close the connection, but returned to the connection pool

C3P0:

C3P0 is an open source JDBC connection pool that implements the JNDI data sources and bindings, support JDBC3 norms and standards JDBC2 extension. It currently use open source project Hibernate, Spring and so on.
Downloads:
1, enter https://www.mchange.com/projects/c3p0/ C3P0 official website (or directly into https://mvnrepository.com/ Maven repository select the corresponding version can be downloaded)
2. Click on "c3p0's site on SourceForge "
3, select the version click on" Download "
use:
1, import c3p0-0.9.5.2-sources.jar and mchange-commons-java-0.2.11- sources.jar two jar package (of course, remember to import mysql the Java-xxxx---connector bin.jar)
2, define the profile name c3p0.properties or c3p0-config.xml, the default path in the project classpath, directly to the file in the src directory to which there is a page "via an XML configuration file", then you can copy the configuration according to the official website template provided.
c3p0-config.xml simple configuration examples:

3, create a core object database connection object ComboPooledDateSource (com.mchange.v2.c3p0.ComboPooledDataSource, you can see step by step to achieve inheritance or in the source code, but eventually realized javax.sql.DataSource)
4, get connected: getConnection

The following example simply creates FIG C3P0 method of:

Druid (Druid):

Alibaba open-source platform to achieve a database connection pool combines the advantages of C3P0, DBCP, PROXOOL such as DB pool, while adding log monitoring, can be a good monitor implementation DB connection pool and SQL can be said for the monitoring and health the DB connection pool (said to be one of the world's best connection pooling).
Download:
can enter this URL http://repo1.maven.org/maven2/com/alibaba/druid/ selected version at the corresponding feed or https://mvnrepository.com/ selecting a corresponding version at
use:
1, import druid-1.1.9.jar (of course, remember to import-Connector-the Java-MySQL-xxxx bin.jar)
2, custom profiles, in the form of properties file, you can name any names, but also can be placed in any directory , commonly called the druid.properties
configuration parameters are shown below:

3, load the configuration file
4, access to a database connection pool object: The factory class DruidDataSourceFactory
5, get connected: getConnection
to create a small pool connected to Druid case:

Spring JDBC :JDBC Template

Spring JDBC is a persistence framework provided by the official spring, and the abstract of jdbc package, eliminating duplicate jdbc repetitive redundant code to make the operation of the database becomes much simpler.
Downloading
into the maven repository https://mvnrepository.com/ after downloading 1, spring-tx-5.1.5.RELEASE 2 , spring-jdbc-5.1.5.RELEASE.jar 3, spring-core-5.1.5.RELEASE .jar 4, spring-beans-5.1.5.RELEASE.jar 5, commons-logging-1.2.jar ( of course you can also download another version of the jar package)
use:
1, into jar package (except the above five the outer bag also a jar jar package jar package database connection pool and database connections)
2, JdbcTemplate create objects, dependent on the data source the dataSource
new new JdbcTemplate (the dataSource)
. 3, a method call to complete JdbcTemplate CRUD operations
update (): for DML DDL statement or statements; CRUD statement
queryForMap (): the query result set will result package is a collection of map (named field column key, value value; and the method returns length for a result set. 1)
the queryForList (): after the query result list is a collection of result sets package (the package to map each record set, then map to set the package list set, the query may be a plurality)
query (): the query result, the package is a JavaBean result (query the RowMapper parameters, typically implemented using BeanPropertyRowMapper class to complete the data JavaBean automatic packaging, new BeanPropertyRowMapper <type> (Type .class).)
queryForObject (): Query Results , the results are wrapped object (typically a function of the polymerization for the query)

And using JdbcTemplate Druid data changes to the database connection pool execution example (which example CRUD operations and similar wording):

And using JdbcTemplate Druid example query a database connection pool execution data (queryForMap () method):

Examples (the queryForList () method) using JdbcTemplate Druid connection pool and data in the database query is executed:

Examples (queryForObject () method) using JdbcTemplate Druid connection pool and data in the database query is executed:

Published 23 original articles · won praise 15 · views 2549

Guess you like

Origin blog.csdn.net/u010511598/article/details/89393447