[Java Study Notes (120)] Introduction to JDBC Programming

This article is published by the official account [Developing Pigeon]! Welcome to follow! ! !


Old Rules-Sister Town House:

One. Database programming

(I. Overview

       The Java Database Connectivity (JDBC) API was released in 1996. Developers connect to the database through this API interface and use Structured Query Language (SQL) to complete operations on the database.

(Two) JDBC driver

1 Overview

       Since the protocols provided by multiple database vendors cannot be unified, Java provides a set of pure Java APIs for SQL access, that is, an API that has nothing to do with the database, and provides a driver manager to allow third-party drivers to register to the driver management In the device, and can connect to a specific database. Programs written through the API can communicate with the drive manager, and the drive manager can communicate with the actual database through the driver. The JDBC driver follows Microsoft's ODBC, which provides a set of programming interfaces for C language to access the database.

2. Driver Classification

       (1) Translate JDBC into ODBC, and use ODBC driver to communicate with database, namely JDBC/ODBC bridge.

       (2) It is composed of some Java programs and some native codes, which are used to communicate with the client API of the database. Before using this driver, you need to install not only the Java class library, but also the platform-related code.

       (3) The pure Java client class library uses a protocol that has nothing to do with the specific database to send the database request to the server component, and then the component translates the database request into a database-related protocol.

       (4) Pure Java class library, which directly translates JDBC requests into database-related protocols.

3. Typical usage of JDBC

       In the traditional C/S architecture, the database is deployed on the server side and the JDBC driver is deployed on the client side. In today's three-tier model, the client does not directly call the database, but calls the middleware layer on the server, and the middleware layer completes the database query operation. This model can classify the visual representation (client) from the business logic (middle layer) and raw data (database), that is, the client can have a variety of manifestations.


(Three) JDBC configuration

1. Register the driver class

       Many JDBC JAR files will automatically register the driver class, of course, we can also manually register, first find out the fully qualified name of the driver class, and use DriverManager to register the driver in two ways. One is to load the driver class in the Java program, that is, to execute the static initializer of the registered driver, such as:

Class.forName(“org.postgresql.Driver”);

       Another way is to set the jdbc.drivers property, which can be specified using command line parameters, such as:

java -Djdbc.drivers=org.postgresql.Driver Name

       Or set system properties in the application, such as:

System.setProperty(“jdbc.drivers”, “org.postgresql.Driver”);

(4) Use JDBC statements

1. Create a Connection object

       First create a connection object Connection through DriverManager, as shown below:

Connection conn = DriverManager.getConnection(url ,username, password);

2. Create Statement object

       Then create the Statement statement object to execute various SQL statements. Each Connection object can create multiple Statement objects, and the same Statement object can be used for multiple unrelated commands and queries, but a Statement object can only have at most one open result set. We need to ensure that all result sets are processed before a Statement object triggers a new query or update statement, because all the result sets of the previous query will be automatically closed. Use try(){} block to automatically close the object.

Statement stat = conn.createStatement();

3. Execute SQL statement

       Execute SQL statements through the Statement object.

(1) executeQuery(command)

       The SELECT query operation returns a ResultSet type object, which can be used to iterate through all query results one row at a time.

ResultSet rs = stat.executeQuery(“SELECT * FROM Books”);

       The order of the rows in the result set is arbitrary, unless the ORDER BY clause is used to specify the order of the rows, the order of the rows is meaningless. After obtaining the result set, the information in it is obtained through the accessor method. Each accessor has two forms, one accepts numeric parameters and the other accepts string parameters. The column number of the database is calculated from 1 .

String isbn = rs.getString(1);
double price = rs.getDouble(“Price”);

(5) Perform query operations

1. Prepared statements

       We don't need to create a new query statement every time we make a query. You can prepare a query statement with a host variable. You only need to fill in a different string for the variable each time you query and you can use it repeatedly. Each host variable is represented by "?", as shown below:

String statement = “SELECT * FROM tb_name WHERE id=?;
PreparedStatement stat = conn.prepareStatement(statement);

       Before executing the prepared statement, you must use the set method to bind the variable to the actual value. The first parameter is the location of the host variable, that is, the first variable, and the second parameter is the value of the variable.

stat.setString(1,3);

       Since string splicing is potentially dangerous, such as quotation marks or user input may cause injection attacks, prepared statements should be used as long as the query involves variables. When the Connection object is closed, the related prepared statement becomes invalid.

2. Read and write LOB

       Data can also store large objects, such as pictures or other data. In SQL, binary large objects are called BLOBs, and character large objects are called CLOBs. To read the LOB, you need to execute a SELECT statement, and then call the getBlob or getClob method on the ResultSet, so that you can get an object of type Blob or Clob.

try(ResultSet result = stat.executeQuery()){
    
    
	if(result.next()){
    
    
		Blob coverBlob = result.getBlob();
		Image coverImage = ImageIO.read(coverBlob.getBinaryStream());
	}
}

       To place the LOB in the database, you need to call createBlob or createBlob on the Connection object, and then obtain an output stream or writer for the LOB, write out the data, and store the object in the database.

3. Get the automatically generated key

       Most databases support a mechanism for automatically numbering rows in the database. These automatically numbered values ​​are used as the primary key. Although JDBC does not provide a solution for automatically generating keys independent of the provider, it provides a way to obtain the automatically generated keys. When inserting a new row, the key of the row is automatically generated, we can get it like this:

stat.executeUpdate(insertStatement, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stat.getGeneratedKeys();
if(rs.next()){
    
    
	int key = rs.getInt(1);
}

(6) Scrollable and updatable result set

1. Scrollable result set

       The default result set is non-scrollable and non-updateable, and different result sets can be obtained by setting the Statement object.

Statement stat = conn.createStatement(type, concurrency);

There are three types of type:

       (1) TYPE_FORWARD_ONLY

       Can't scroll

       (2) TYPE_SCROLL_INSENSITIVE

       It can be scrolled, but it is not sensitive to database changes, that is, the database will not be updated in real time.

       (3) TYPE_SCROLL_SENSITIVE

       It can be scrolled and is sensitive to database changes.

There are two types of concurrency:

       (1) CONCUR_READ_ONLY

       The result set cannot be used to update the database.

       (2) CONCUR_UPDATABLE

       The result set can be used to update the database.


2. Updatable result set

       If you want to edit the data in the result set and automatically reflect the data changes in the result set to the database, you need to use an updatable result set.

Statement stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

(7) Row set

       The connection between the client and the database is not necessarily efficient. In many cases, connection resources are wasted, so we use rowsets to solve this problem. The RowSet interface extends from the ResultSet interface, but there is no need to maintain a link with the database.

1. Build a row set

RowSetFactory fac = RowSetProvider.newFactory();
CachedRowSet crs = fac.createCachedRowSet();

       There are several types of rowset, all of which extend the RowSet interface.

2. Cached rowset

       A cached row set contains all the data in a result set. After the database is disconnected, the row set can still be used, and the data in the row set can be modified at the same time, and then sent to the database to update and modify through the displayed request.

(8) Metadata

       JDBC also provides detailed information about the database and its table structure, namely metadata. Different from the actual data stored in the database, we can obtain three types of metadata, one is the metadata of the database, and the other is the metadata of the result set. Data, one type is metadata of prepared statement parameters. Get metadata by getting a DatabaseMetaData object from the database connection.


(9) Affairs

1 Overview

       A group of statements constitute a transaction. When all the statements are successfully executed, the transaction can be committed. Otherwise, if one of the statements encounters an error, the transaction will be rolled back as if no statement has been executed.


2. JDBC transaction programming

       By default, the database connection is in auto-commit mode, that is, once each SQL statement is executed, it will be submitted to the database. Once the command is submitted, it cannot be rolled back. When using transactions, turn off this default value. .

conn.setAutoCommit(false);

conn.commit();
conn.rollback();

3. Storage point

       When using certain drivers, savepoints are used to more fine-grained control of the rollback operation. Creating a savepoint means that you only need to return to this point, rather than abandon the entire transaction. When the save point is not needed, release it.

Statement stat = conn.createStatement();
state.executeUpdate(command1);
Savepoint svpt = conn.setSavepoint();
stat.execcuteUpdate(command2);
if() conn.rollback(svpt);
conn.commit();
conn.releaseSavepoint(svpt);

(10) Database connection pool mechanism

       The JDBC specification provides implementers with a means to implement connection pool services, but JDK does not implement database connection pools, and JDBC drivers usually do not include this service. On the contrary, web container and application server developers will provide connection pools. The realization of the service. The connection pool mechanism can usually also be used for prepared statements.

Guess you like

Origin blog.csdn.net/Mrwxxxx/article/details/113530660