How to connect Java programs to a database _java

Source: Internet
Author: User
Tags driver manager odbc access database

A network relational database application system is a three-tiered structure. The client and the server use the network connection, the client-side application communicates with the server-side database program according to the communication Protocol; The database service program communicates with the database management system through the SQL command.

There are two ways to connect Java programs to the database. One is to connect to the database using a JDBC-ODBC bridge, one that is connected to the database with a pure Java JDBC driver.
connecting to a database using the Jdbc-odbc bridge

The Java program uses the Jdbc-odbc Bridge to connect to the database, and the process by which the Java program communicates with the database is:
The database application first issues an API call to the ODBC Driver Manager, which the ODBC driver Manager converts to an ODBC driver for the database management system, which translates the call into a data input/output call to the operating system. Finally, the operating system obtains the actual data stepwise return from the database.

Database programming to set up the data source first, set the data source in ODBC as follows:
Open the Administrative Tools in Windows Control Panel. For Windows XP: Select Performance Maintenance >> Administrative Tools >> Data Source (ODBC); For Windows 2000: Select Administrative Tools >> data source.
Open the data source. The ODBC Data Source Administrator dialog box appears, displaying the existing data source name.
Select User DSN, click the Add button, and the Install Data Source Driver dialog box appears. Access (*.mdb) data source, click Finish, and the Create Data Source dialog box appears, type the name of the data source you want to create, and select a database table for the data source you created.
Click the Select button in the database area to select the database table you want. When you want to grant access levels to the data source, click the Advanced button. After you set the login name and password, click OK to complete the configuration of the Access database in ODBC Manager.
If you do not have a database table, you need to create a database table.

Data source is the database, in the setting of the data source, the Java program to access the database table, but also to establish a JDBC-ODBC bridge, so that the program and the database connection. Later, the program can send SQL statements to the database to handle the results returned by the database. Java Database connection JDBC (Java DB connectivity) consists of a set of classes and interfaces written in the Java language, which is the Java program and database connection API. It can do the following three things: Establish a connection to a database, send SQL statements to a database, and process the results of a database return.

Calling the class method Class.forName (String s) creates a JDBC-ODBC bridge. For example, code:

  try{
    class.forname ("Sun.jdbc.odbc.JdbcOdbcDriver");
  } catch (Exception e) {}


Loaded the driver for the Java program.
The example describes the method Connectbyjdbcodbc () that connects to the database, which connects the database by the given database URL, user name, and password, and returns null if the connection succeeds, the method returns the Connection object, and the connection is unsuccessful.

public static connection Connectbyjdbcodbc (string URL, string username, string password) {
  connection con = null;
  try{
    class.forname ("Sun.jdbc.odbc.JdbcOdbcDriver");  Load ODBC drivers
  }
  catch (Exception e) {
    e.printstacktrace ();
    return null; Connection failed
  }
  try{
    con = drivermanager.getconnection (URL, username, password);
  }
  catch (Sqlexceotuib e) {
    e.printstacktrace ();
    return null; Connection unsuccessful
  } return
  con;//connection succeeded
}

The following code is a call to the Connectbyjdbcodbc () method, the database connection is successful, pop-up database Connection Success Information window, otherwise pop-up database connection unsuccessful Information window.

if ((con = CONNECTBYJDBCODBC ("Jdbc:odbc:redsun", "Xia", "1234"))!= null) {
  joptionpane.showmessagedialog (null, " Database connection Successful ");
  try{
    con.close ();
    con = null;
  }
  catch (Solexception e) {}
}
else
  joptionpane.showmessagedialog (NULL, "database connection failed");

Implement a database connection with a pure Java JDBC driver

Java programs can also connect to the database with a pure Java JDBC driver. This method is more widely used, but needs to download the appropriate driver package, because the different database connection code may be different, connect different databases, loading drivers may also be different. For example, a driver connecting to SQL Server is downloaded from the www.msdn.com Web site with 3 packages: Msbase.jar,mssqlserver.jar and Msutil.jar, and requires that the 3 packages be placed under the Jdk\jre\lib\ext\ directory. or set its placement position in classpath.

The process of implementing a database connection using a pure Java JDBC driver is as follows:
Load the driver. There are two ways to load a driver:
One is to add the driver to the Java.lang.System property jdbc.drivers. This is a list of driver class names loaded by the DriverManager class, separated by colons.
Another way is to load the specified driver using the Class.forName () method in the program after downloading the driver from the relevant web site. For example:

  Class.forName ("Com.microsoft.jdbc.sqlserver.SQLServerDriver");


Creates a URL for the specified database. The URL object for a database resembles a Uniform Resource locator for a network, in the form of:

  Jdbc:subprotocol:subname://hostname:port:databasename=xxx


Subprotocol is the database connection mechanism supported by some driver, SubName is the specific name under the current connection mechanism, hostname is the host name, port is the corresponding connection port, and DatabaseName is the database name to be connected. For example, the following code can be a URL to a database:

  Jdbc:microsoft:sqlserver://localhost:1433;databasename=ksinfo


The URL of the database describes the mechanism provided by Miscrosoft, using the Sqlserve driver, to access the Ksinfo database on the local computer via port 1433.
Establish a connection. The Driver Manager (DriverManager) method getconnection () establishes a connection.

"Example" describes the static method Connectbyjdbc () for a database connection, which connects the database by the given database URL, user name, and password, or False if the connection succeeds, the method returns True, and the connection is unsuccessful.

public static Connection conectbyjdbc (string URL, string username, string password) {
  Connection con = null;
  try{
    class.forname (//Load Specific driver
    "Com.microsoft.jdbc.sqlserver.SQLServerDriver");
  }
  catch (Exception e) {
    e.printstacktrace ();
    return null; Connection failed
  }
  try{
    con = drivermanage.getconnection (URL, username, password);
  }
  catch (SQLException e) {
    e.printstacktrace ();
    return null; Connection failed
  } return
  con;//connection succeeded
}

Related Article

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.