Connecting to a database with JDBC

Source: Internet
Author: User
Tags driver manager odbc

It is estimated that nearly half of all software development involves customer (machine)/server operations. One of the great capabilities that Java can guarantee for itself is to build platform-independent client/server database applications. In Java 1.1, this assurance is implemented through a Java database connection (JDBC).
One of the main problems with the database is the size wars between companies. There is indeed a "standard" database language, the "Structured Query Language" (SQL-92), but it is often necessary to know exactly which database company you want to deal with, otherwise it is extremely problematic, despite the existence of the so-called "standard". JDBC is geared toward "platform-independent" design, so you don't have to be concerned about what database product you're using when you're programming. However, it is still possible to make calls to specific features of some database companies from JDBC, so it is still not willful.
As with many of the APIs in Java, JDBC has been simplified as much as possible. The method call we emit corresponds to what is taken for granted when collecting data from a database: Connecting to a database, creating a statement and executing a query, and then processing the result set.
To achieve this "platform-independent" feature, JDBC provides us with a "driver manager" that dynamically maintains all the driver objects required for database queries. So if you want to connect a different kind of database developed by three companies, you need three separate driver objects. The driver object is automatically registered by the Driver manager at load time and can be forcibly loaded with Class.forName ().
To open a database, you must create a "database URL" that specifies the following three things:
(1) using "JDBC" to indicate that you want to use JDBC.
(2) "Sub-Protocol": The name of the driver or the name of a database connection mechanism. Since the design of JDBC absorbs a lot of inspiration from ODBC, the first seed protocol that can be chosen is the "Jdbc-odbc Bridge", which is specified with the "ODBC" keyword.
(3) Database identifiers: Vary with the database drivers used, but generally provide a more logical name, mapped by the database management software to a physical directory that holds the datasheet. In order to have any meaning to your database identifier, you must register with your own database management software for your favorite name (the specific process of registration varies with the operating platform).
All this information is compiled uniformly into a string, the database URL. For example, if you want to connect to a database that is identified as "people" via the ODBC Child Protocol, the corresponding database URL can be set to:
String Dburl = "Jdbc:odbc:people"
If you are using a network connection, the database URL also needs to contain information that identifies the remote machine.
Once you are ready to connect to the database, you can invoke the static method Drivermanager.getconnection () to pass the URL of the database and the username password required to enter that database. The resulting return result is a connection object that can be used to query and manipulate the database.
The following example opens a contact information database and queries the last name of a person based on the parameters provided by the command line. It selects only the names of those who have an e-mail address, and then prints out all the people who meet the query criteria:

: Lookup.java//Looks up email addresses into a//local database using JDBC import java.sql.*;
    public class Lookup {public static void main (string[] args) {String Dburl = "Jdbc:odbc:people";
    String user = "";
    String password = "";
      try {//Load the driver (registers itself) Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
      Connection C = drivermanager.getconnection (dburl, user, password);
      Statement s = c.createstatement (); SQL Code:resultset r = S.executequery ("Select a, Last, EMAIL" + "from people.)
          CSV people "+" WHERE "+" (last= ' + args[0] + "')" + "and (EMAIL is not Null) +
      "ORDER by a");  while (R.next ()) {//capitalization doesn ' t matter:System.out.println (r.getstring ("last") + ",
      "+ r.getstring (" a ") +": "+ r.getstring (" EMAIL ")); } s.close (); //Also closes ResultSet} catch (Exception e) {e.printstacktrace (); }
  }
} ///:~

As you can see, the database URL is created in exactly the same way as we described earlier. In this case, the database is not password protected, so both the username and password are empty strings.
After the connection is built with Drivermanager.getconnection (), you can then create a statement (statement) object based on the result connection object, which is implemented using the Createstatement () method. Based on the result statement, we can call ExecuteQuery () to pass a string containing the SQL-92 standard SQL statement (soon we'll see how to automatically create such statements, so there's no need to know more about SQL here).
The ExecuteQuery () method returns a ResultSet (result set) object that is very similar to the successor: the next () method moves the successor to the next record in the statement, and returns null if the end of the result set is reached. We can definitely return a ResultSet object from ExecuteQuery (), even if the query result is an empty set (that is, no violation will occur). Note You must call next () once before attempting to read any record data. If the result set is empty, the first call to Next () returns false. For each record in the result set, you can use the field name as a string (and, of course, other methods) to select a different field. Also note that the case of the field name is irrelevant--sql the database does not care about this problem. To determine which type to return, you can call GetString (), GetFloat (), and so on. By this time, we've got our own database data in Java's original format, and then we can do whatever we want with Java code.

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.