JDBCTM Guide: Getting Started 2-connections

Source: Internet
Author: User
Tags file system ftp connect odbc sql naming convention string file transfer protocol
JDBCTM Guide: Getting Started 2-connections
2-Connection
This overview is quoted in the book Jdbctm Database Access from Javatm:a Tutorial and annotated Reference. JavaSoft is currently preparing the book. This book is a tutorial and an important reference manual for JDBC, which will be published as part of the Java family in the spring of 1997 by Addison-wesley Publishing Company.


2.1 Overview
The Connection object represents a connection to the database. The connection process includes the executed SQL statement and the results returned on that connection. An application can have one or more connections to a single database, or it can be connected to many databases.


2.1.1 Open Connection
The standard way to establish a connection with a database is to invoke the Drivermanager.getconnection method. This method accepts a string containing a URL. The DriverManager class, known as the JDBC Management layer, will attempt to locate a driver that can connect to the database represented by that URL. The DriverManager class contains a list of registered Driver classes. When the method getconnection is invoked, it checks each driver in the manifest until it finds a driver that can connect to the database specified in the URL. Driver's method connect uses this URL to establish the actual connection.

Users can invoke the Driver method directly by bypassing the JDBC management layer. This is useful in exceptional cases where two drives can be connected to the database at the same time, and the user needs to explicitly select a particular drive. But in general, it would be simpler to let the DriverManager class handle open connections.

The following code shows how to open a connection to a database that is located in the URL "Jdbc:odbc:wombat". The user identifier used is "Oboy" and the password is "12Java":

String url = "Jdbc:odbc:wombat";
Connection con = drivermanager.getconnection (URL, "Oboy", "12Java");

2.1.2 The general usage URL
Since URLs are often confusing, we'll start with a simple description of the generic URL before we discuss the JDBC URL.

The URL (Uniform Resource Locator) provides the information needed to locate resources on the Internet. It can be imagined as an address.

The first part of the URL specifies the protocol used to access the information followed by a colon. Commonly used protocols are "FTP" (for "File Transfer Protocol") and "http" (for Hypertext Transfer Protocol). If the protocol is "file", it means that the resource is on a local file system rather than on the Internet (the following example is used to represent the part we describe; it is not part of the URL).

Ftp://javasoft.com/docs/JDK-1_apidocs.zip
Http://java.sun.com/products/jdk/CurrentRelease
File:/home/haroldw/docs/books/tutorial/summary.html

The remainder of the URL (after the colon) gives information about where the data resource is located. If the protocol is file, the remainder of the URL is the path to the files. For FTP and HTTP protocols, the remainder of the URL identifies the host and optionally gives a more detailed address path. For example, the following is the URL of the JavaSoft home page. The URL identifies only the host:

Http://java.sun.com

Starting from this homepage, you can go to many other pages, one of which is the JDBC home page. The JDBC home page URL is more specific and looks like this:

Http://java.sun.com/products/jdbc

2.1.3 JDBC URL
The JDBC URL provides a way to identify the database and enable the appropriate driver to identify the database and establish a connection to it. In fact, the driver programmer will decide what JDBC URL to use to identify the specific driver. Users do not have to care about how to form a JDBC URL; they only have to use the URL provided with the driver they are using. The role of JDBC is to provide certain conventions that driver programmers should follow when constructing their JDBC URLs.

Because JDBC URLs are used with a variety of different drivers, these conventions should be flexible. First, they should allow different drivers to name the database using different scenarios. For example, the ODBC Sub-protocol allows (but does not require) a URL to contain property values.

Second, the JDBC URL should allow driver programmers to incorporate all the information they need. This allows you to open the database connection to the applet that is going to talk to a given database without requiring the user to do any system administration work.

Third, the JDBC URL should allow some degree of indirection. That is, the JDBC URL can point to the logical host or database name, which is dynamically converted to the actual name by the network naming system. This allows the system administrator to not have to declare a specific host as part of the JDBC name. There are a number of network naming services, such as DNS, NIS, and DCE, and there is no limit to which naming service to use.

The standard syntax for the JDBC URL is shown below. It consists of three parts, separated by a colon:

Jdbc::

The three parts of the JDBC URL can be broken down as follows:


jdbc─ agreement. The protocol in the JDBC URL is always jdbc.


-Name of the driver name or database connection mechanism (this mechanism can be supported by one or more drivers). A typical example of a child protocol name is "ODBC", which is reserved specifically for the URL that specifies the name of the ODBC-style data resource. For example, to access a database through the Jdbc-odbc bridge, you can use the URL shown below:
Jdbc:odbc:fred

In this case, the Child protocol is "ODBC" and the child name "Fred" is a local
ODBC data resources.

If you want to use the network naming Service (so that the database name in the JDBC URL does not have to be the actual name), the naming service can be a child protocol. For example, you can use a URL that looks like this:

Jdbc:dcenaming:accounts-payable

In this case, the URL specifies that the local DCE naming service should
The database name "accounts-payable" resolves to a more specific
The name that can be used to connect to the real database.


-a method of identifying a database. A child name can vary according to a different child protocol. It can also have a child name that contains any internal syntax selected by the driver programmer. The purpose of using a child name is to provide sufficient information for locating the database. In the previous precedent, because ODBC will provide the rest of the information, it is sufficient to use "Fred". However, the database located on the remote server requires more information. For example, if the database is accessed over the Internet, the network address should be included as part of the child name in the JDBC URL and must follow the standard URL naming convention as follows:
Host Name: Port/Sub Protocol

If "Dbnet" is a protocol used to connect a host to the Internet, the JDBC URL is similar:

Jdbc:dbnet://wombat:356/fred

2.1.4 "ODBC" sub-protocol
Sub-Protocol ODBC is a special case. It is reserved for the URL that specifies the name of the ODBC-style data resource and has the following attributes: Allows you to specify any number of property values after a child name (data resource name). The complete syntax for the ODBC Child Protocol is:


jdbc:odbc:[;=]*

Therefore, the following are the legal JDBC:ODBC names:

Jdbc:odbc:qeor7
Jdbc:odbc:wombat
Jdbc:odbc:wombat; cachesize=20; Extensioncase=lower
Jdbc:odbc:qeora; Uid=kgh; Pwd=fooey

2.1.5 Registration Sub-protocol
A driver programmer can retain a name to use as a child protocol name for a JDBC URL. When the DriverManager class adds this name to the registered driver manifest, the driver that retains the name should recognize the name and establish a connection to the database it identifies. For example, ODBC is reserved for JDBC-ODBC bridges. Example bis, assuming that there is a Miracle company, it may register "Miracle" as a child protocol attached to the JDBC driver on its Miracle DBMS, so that the name cannot be used by anyone else.

JavaSoft is currently responsible for registering the JDBC Child protocol name as an unofficial agent. To register a child agreement name, send an e-mail message to the following address:

Jdbc@wombat.eng.sun.com

2.1.6 Send SQL statements
Once a connection is established, it can be used to transfer SQL statements to the database it is involved in. JDBC does not impose any restrictions on the types of SQL statements that can be sent. This provides a great flexibility to allow specific database statements or even non-SQL statements to be used. However, it requires the user to be responsible for ensuring that the database involved can process the SQL statements sent, otherwise it will reap the consequences. For example, if an application tries to send a stored program call to a DBMS that does not support the stored program, it fails and throws an exception. JDBC requires that the driver should at least provide ANSI SQL-2 Entry level functionality to qualify as JDBC Standard TM. This means that users can at least rely on this standard level of functionality.

JDBC provides three classes for sending SQL statements to a database. The three methods in the Connection interface can be used to create instances of these classes. These classes and how they are created are listed below:


The statement─ is created by the method createstatement. The Statement object is used to send a simple SQL statement.
The preparedstatement─ is created by the method Preparestatement. The PreparedStatement object is used to send an SQL statement with one or more input parameters (in parameters). PreparedStatement has a set of methods for setting the value of the in parameter. When the statement is executed, these in parameters are sent to the database. PreparedStatement instances extend the Statement, so they all include the Statement method. The PreparedStatement object may be more efficient than the Statement object because it has been precompiled and stored there for future use.
The callablestatement─ is created by the method Preparecall. The CallableStatement object is used to execute the SQL store program-a set of SQL statements that can be invoked by name, just like the call of a function. The CallableStatement object inherits from PreparedStatement the method used to process the in parameter, and also adds methods for handling out and INOUT parameters.

The methods provided below can quickly determine which Connection method is applied to create different types of SQL statements:


The Createstatement method is used to:


Simple SQL statement (with no parameters)


The Preparestatement method is used to:


SQL statement with one or more in parameters


Simple SQL statements that are often executed


The Preparecall method is used to:


Calling stored procedures


2.1.7 Affairs
A transaction consists of one or more such statements that have been executed, completed, and committed or restored. When a method commit or rollback is invoked, the current transaction ends and another transaction begins.

By default, new connections are in autocommit mode. That is, when the statement is executed, the Commit method is automatically invoked on that statement. In this case, because each statement is committed separately, a transaction consists of only one statement. If autocommit mode is disabled, the transaction will not end until the commit or Rollback method is explicitly called, so it includes all the statements that have been executed since the last time the commit or Rollback method was invoked. For the second case, all statements in the transaction are committed or restored as groups.

A method commit makes any changes made to the database by the SQL statement permanent, and it frees all locks held by the transaction. and method Rollback will discard those changes.

Sometimes the user does not want this change to take effect until another change takes effect. This can be achieved by disabling autocommit and combining two updates in a single transaction. If all two updates are successful, the Commit method is invoked to make the two update results permanent, and if either or two of the updates fail, the Rollback method is called to return the value to the value before the update was made.

Most JDBC drivers support transactions. In fact, JDBC-compliant drivers must support transactions. The information given by DatabaseMetaData describes the level of transaction support provided by the DBMS.


2.1.8 Transaction ISOLATION LEVEL
If the DBMS supports transaction processing, it must have some way of managing the conflicts that can occur when two transactions are operating on a single database at the same time. Users can specify transaction isolation levels to indicate how much effort the DBMS should take to resolve potential conflicts. For example, what happens when a transaction changes a value and the second transaction reads the value before the change is committed or restored? If the change value read by the second transaction will be invalid after the first one is restored, is it permissible to allow this conflict? The JDBC user can use the following code to instruct the DBMS to allow reading of the value ("dirty read") before the value is committed, where con is the current connection:

Con.settransactionisolation (transaction_read_uncommitted);

The higher the transaction isolation level, the more effort is spent to avoid conflicts. The Connection interface defines level five, where the lowest level specifies that the transaction is not supported at all, and the highest level specifies that any other transaction must not make any changes to the data that the transaction is reading when the transaction is operating on a database. Typically, the higher the isolation level, the slower the application executes (because of the increased resource consumption for locking and fewer concurrent operations between users). When deciding what isolation level to adopt, developers must weigh the performance requirements against the need for data consistency. Of course, the level of actual support depends on the capabilities of the DBMS involved.

When you create 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 for the remainder of the connection process. To change the transaction isolation level for only one transaction, you must set the transaction before it starts and reset it after the transaction ends. We do not advocate making changes to the transaction isolation level in the middle of a transaction, as this will immediately trigger the invocation of the commit method so that any changes made prior to it become permanent.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.