"JSP learning - comprehensive analysis JDBC (2)"

xiaoxiao2021-03-06  31

How to establish a JDBC connection? The Connection object represents the connection to the database. The connection process includes the resulting SQL statement and the result returned on the connection. An application can have one or more connections with a single database, or can be connected to many databases.

Open connection

The standard method for establishing a connection with the database is to call the DriverManager.getConnection method. This method accepts a string containing a URL. The DriverManager class (ie, the so-called JDBC Management) will try to find a driver that can be connected to the database represented by the URL. The DRIVERMANAGER has a list of registered DRIVER classes. When the method getConnection is called, it will check each driver in the list until a driver that can be connected to the database specified in the URL. Driver's method Connect uses this URL to establish a practical connection.

The user can bypass the JDBC management directly call the Driver method. This will be useful in the following special circumstances: When the two drivers can be connected to the database, the user needs to expressly select the specific drive. But in general, let DRIVERMANAGER class handle this kind of job will be simpler.

The following code shows how to open a connection to a database located at the URL "JDBC: ODBC: Wombat". The user identifier used is "freely", the password is "EC":

String Url = "JDBC: ODBC: Wombat"; Connection Con = DriverManager.getConnection (URL, "Freely", "EC");

2. URL generally usage

Since the URL often causes confusion, we will first make a brief description of the general URL and then discuss JDBCURL. URL (Uniform Resource Locator) provides information required to locate resources on the Internet. You can imagine it as an address. The first part of the URL specifies the protocol used to access the information, which is always following the colon. Commonly used protocols have "FTP" (representing "File Transfer Protocol") and "HTTP" (represents "Hypertext Transfer Protocol"). If the protocol is "file", it means that the resource is on a local file system, not on the Internet (the following example is used to represent the part we described; it is not a component component).

FTP: //javasoft.com/docs/jdk-1_apidocs.zip http://java.sun.com/products/jdk/currentrelease file: /Home/HaroldW/docs/books/tutorial/summary.html

The remaining part of the URL (behind the colon) gives the relevant information of the location where the data resource is located. If the protocol is file, the remaining part of the URL is the path to the file. For FTP and HTTP protocols, the remaining parts of the URL identify the host and optionally give a more detailed address path. For example, the following is the URL of the JavaSoft home page. The URL only identifies the host: http://java.sun.com. From this homepage, you can go to many other web pages, one of which is the JDBC home page. The URL of the JDBC home page is more specific, it is specifically expressed as: http://java.sun.com/products/jdbc

3. JDBC URL

The JDBC URL provides a method of identifying a database that enables the corresponding driver to identify the database and establish a connection thereto. In fact, the driver programmer will determine what JDBC URL identifies a particular driver. Users don't have to care about how to form a JDBC URL; they only need to use the URL provided with the drivers used. JDBC's role is to provide some conventions, and the driver programmer should follow these conventions when constructing their JDBC URL. Since the JDBC URL should be used with a variety of drivers, these agreements should be very flexible. First, they should allow different drivers to use different scenarios to name the database. For example, the ODBC sub protocol allows (but not required) URL contains attribute values.

Second, the JDBC URL should allow driver programmers to be encapsulated in it. This allows you to open a database connection with the applet to a given database dialog, without requiring users to do any system management.

Finally, the JDBC URL should allow some degree of indirectness. That is, the JDBC URL can point to the logical host or database name, and this logical host or database name will dynamically convert to the actual name by the network naming system. This allows the system administrator to declare a particular host as part of the JDBC name. Network naming services (such as DNS, NIS, and DCE) have a variety of, but no restrictions on which naming service used. The standard syntax of the JDBC URL is as follows. It consists of three parts, each part is separated by colon: JDBC: BR> JDBC URL can be decomposed as follows:

(1) JDBC protocol: The protocol in the JDBC URL is always JDBC.

(2) : Driver name or database connection mechanism (this mechanism can be supported by one or more drivers). A typical example of the sub-protocol name is "ODBC", which is specifically reserved for the URL of the data resource name for specifying the ODBC style. For example, in order to access a database through a JDBC-ODBC bridge, you can use the URL: JDBC: ODBC: BOOK. In this example, the child protocol is "ODBC", the child name "book" is the local ODBC data resource. If you want to use a network naming service (such a database name in the JDBC URL does not have to be an actual name), the naming service can be used as a sub-protocol. For example, the URL: JDBC: DCENAMING: JDBC: DCENAMING: JDBC: DCENAMING: JDBC: In this example, the URL specifies the local DCE naming service to resolve the database name "Accounts" into a more specific name to connect the real database.

(3) : Method for identifying the database. The child name can vary depending on the sub-protocol. It also has a sub-name of a child (including any internal syntax selected by the driver programmer). The purpose of using sub-name is to provide sufficient information for positioning the database. In the precedent, since the ODBC will provide information on the remaining part, it is enough to use "BOOK". However, the database on the remote server requires more information. For example, if the database is accessed through the Internet, a part of the network address is included as a sub-name in the JDBC URL, and must follow the standard URL naming convention as shown below: // host name: port / child protocol.

Assuming "DBNET" is a protocol for connecting a host to the Internet, the JDBC URL should be: JDBC: DBNET: // Wombat: 356 / fred. 4. "ODBC" sub-protocol

Sub protocol ODBC is a special case. It is preserved for the URL for specifying the data resource name of the ODBC style, and has the following characteristics: Allow any multiple attribute values ​​to be specified after the child name (data resource name). The full syntax of the ODBC sub protocol is:

JDBC: ODBC: [; = ], therefore, the following is a legal JDBC: ODBC Name: JDBC: ODBC: QEOR7 JDBC: ODBC: Wombat JDBC: ODBC: Wombat; Cachesize = 20; extensioncase = Lower JDBC: ODBC: QEORA; UID = KGH; PWD = fooey

5. Registered Sub-agreement

The driver programmer retains a name to use it as a sub protocol name of the JDBC URL. When the DRIVERMANAGER class adds this name to the registered driver list, the name of the name should be recognized and connected to the database identified by it. For example, ODBC is reserved for a JDBC-ODBC bridge. Suppose there is a Miracle, which may register "miracle" as a sub-protocol to connect to the JDBC driver on its Miracle DBMS, so that others cannot use this name.

JavaSoft is currently responsible for registering the JDBC sub protocol name as an informal agent. To register a sub-protocol name, send an email to the following address: jdbc@wombat.eng.sun.com.

6. Send SQL statement

Once the connection is established, it can be used to transmit the SQL statement to the database it involved. JDBC does not add any restrictions on the type of SQL statement that can be sent. This provides a lot of flexibility that allows specific database statements or even non-SQL statements. However, it requires the user to ensure that the database involved can handle the sent SQL statement, otherwise you will be self-sufficient. For example, if an application tries to send a storage program to the DBMS that does not support the storage program, it will fail and will throw an exception. JDBC requires a driver to provide at least ANSI SQL-2 Entry Level functionality to be in accordance with JDBC standard TM. This means that users can at least trust this standard level.

JDBC provides three classes to send SQL statements to the database. Three methods in the Connection interface can be used to create instances of these classes. These classes are listed below and their creation methods:

(1) Statement: Created by method CreateStatement. The Statement object is used to send a simple SQL statement.

(2) prepaaredStatement: is created by the method PrepareStatement. The PreparedStatement object is used to send a SQL statement with one or more input parameters (IN parameters). PreparedStatement has a group of methods for setting the value of the IN parameter. These IN parameters will be sent to the database when performing statements. The example of PreparedStatement extends Statement, so they all include a STATEMENT method. The PreparedStatement object is likely to be higher than the STATEMENT object, as it has been precompiled and stored there for future use. (3) CallableStatement: Created by method prepareCall. The CallableStatement object is used to execute SQL storage programs - a set of SQL statements that can call (as in the call of the icon "by name. The CallableStatement object inherits the method of processing the IN parameter from PreparedStatement, and also adds a method for processing OUT parameters and inout parameters.

However, the CreateStatement method is usually used for simple SQL statements (without parameters), and the PrepareStatement method is used to bring one or more IN parameters or a simple SQL statement that is often executed, and the prepareCall method is used to call the stored process. .

7. Transaction

The transaction consists of one or more such statements: these statements have been executed, completed and submitted or restored. When the method commit or rollback is called, the current transaction ends, and another transaction begins. By default, the new connection will be in automatic submission mode. That is, after the expression is performed, the COMMIT method will be called automatically. In this case, since each statement is submitted separately, a transaction consists only by one statement. If automatic submission mode is disabled, the transaction will wait until the CommT or Rollback method is explicitly invoked, so it will include all the statements that have been executed since the last call commit or rollback method. For the second case, all statements in the transaction will be submitted or restored as a group.

Methods Commit makes any changes made by the SQL statement to the database, which will also release all locks held by the transaction. The method ROLLBACK will discard those changes. Sometimes the user does not want this to take effect before another change. This can be achieved by disabling automatic submission and combining two updates in a transaction. If the two updates are successful, call the commit method so that the two update results become permanent; if one or two updates fails, call the ROLLBACK method to restore the value to be updated. value.

Most JDBC drivers support transactions. In fact, drivers that meet JDBC must support transactions. DatabaseMetadata gives the information given by DBMS.

8. Transaction isolation level

If DBMS supports transaction processing, it must have some way to manage two transactions simultaneously conflicts with a database. Users can specify a transaction isolation level to indicate how DBMS should spend more energy to solve potential conflicts. For example, what should I do when transaction changes a certain value and the second transaction reads this value before the change is submitted or restored.

Suppose the first transaction is restored, the change value read by the second transaction will be invalid, then this conflict can be allowed? The JDBC user can use the following code to indicate that the DBMS allows the value ("DIRTY read") to be read before the value is submitted, where CON is current connection: con.settransactioniSolation; transaction isolation level is higher, to avoid conflict The more energy is also. The Connection interface defines five levels, where the lowest level specifies that the transaction is not supported, and the highest level specifies that any other transaction does not change the data that the transaction is being read when the transaction is operated in a database. Typically, the higher the isolation level, the slower the speed of the application execution (due to the increase in resources for lock, and the concurrent operation between the user is reduced). When deciding which isolation level, developers must trade between performance requirements and data consistency requirements. Of course, the actual level can be supported depends on the function of the DBMS involved.

When creating a Connection object, its transaction isolation level depends on the driver, but is usually the default value of the database involved. Users can change the transaction isolation level by calling the SetisolationLevel method. The new level will take effect within the remainder of the connection process. If you want to change only a transaction isolation level of a transaction, you must set it before the transaction begins, and reset after the end of the transaction. We do not advocate the changes to the transaction isolation level in the middle of the transaction, as this will immediately trigger the call to the COMMIT method, so that any changes made before this will become permanent.

转载请注明原文地址:https://www.9cbs.com/read-69203.html

New Post(0)