Ways to connect databases and create programs using the JDBC API in Java programming _java

Source: Internet
Author: User
Tags db2 finally block garbage collection stmt sybase

JDBC Connection Database

The programming involved in building a JDBC connection is fairly straightforward. Here are the simple four steps:

    1. Import JDBC Package: Add import statements to Java Program import required classes in Java code.
    2. Registering the JDBC driver: This step will cause the JVM to load the required drivers into memory so it can implement the JDBC request.
    3. Database URL formulation: This is to create a properly formatted address to point to the database to which you want to connect.
    4. To create a Connection object: Finally, the code calls the DriverManager object's getconnection () method to establish the actual database connection.

To import a JDBC package:
The import statement tells the Java compiler where to find the class that is referenced in code and placed at the beginning of your source.

Using the standard JDBC package, which allows you to select, INSERT, UPDATE, and delete data from SQL tables, add the following imports to your source code:

Import java.sql.*; For standard JDBC programs
import java.math.*.//For BigDecimal and BigInteger support

To register the JDBC driver:
Before using it, you must register your driver in the program. The registration driver is loaded into memory by the Oracle driver's class file so that it can be used as the implementation of the JDBC interface.

Need to do this registration only once in your program. You can register one driver in one of the following two ways.

Method (I)-Class.forName ():
The most common way to register a driver is to use the Java Class.forName () method to dynamically load the driver's class file into memory, and it will automatically register it. This method is desirable because it allows driver registration to be configured for easy portability.

The following example uses Class.forName () to register an Oracle driver:

try {
  class.forname ("Oracle.jdbc.driver.OracleDriver");
}
catch (ClassNotFoundException ex) {
  System.out.println ("error:unable to load Driver class!");
  System.exit (1);
}

You can use the getinstance () method to resolve incompatible JVMs, but there are two additional exceptions that are written as follows:

try {
  class.forname ("Oracle.jdbc.driver.OracleDriver"). newinstance ();
}
catch (ClassNotFoundException ex) {
  System.out.println ("error:unable to load Driver class!");
  System.exit (1);
catch (Illegalaccessexception ex) {
  System.out.println ("error:access problem while loading!");
  System.exit (2);
catch (Instantiationexception ex) {
  System.out.println ("Error:unable to instantiate driver!");
  System.exit (3);
}

Method (ii)-Drivermanager.registerdriver ():
The second way you can use it to register a driver is to use the Staticdrivermanager.registerdriver () method.

Should, if the use of incompatible JDK JVM, such as Microsoft provides a use of the Registerdriver () method.

The following example uses Registerdriver () to register an Oracle driver:

try {
  Driver mydriver = new Oracle.jdbc.driver.OracleDriver ();
  Drivermanager.registerdriver (mydriver);
}
catch (ClassNotFoundException ex) {
  System.out.println ("error:unable to load Driver class!");
  System.exit (1);
}

Database URL Development:
When loading a driver, you can establish a connection using the Drivermanager.getconnection () method in the program. For easy reference, let's list three overloaded Drivermanager.getconnection () methods:

    1. getconnection (String URL)
    2. getconnection (String URL, Properties prop)
    3. getconnection (string url, string user, string password)

Here, each form requires a database URL. The URL of the database is to point to the database address.

The development of a database URL is most used in establishing connection-related.

The following table lists the popular JDBC driver names and the URL of the database.

RDBMS JDBC driver name URL format

MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/databasename
ORACLE oracle.jdbc.driver.OracleDriver jdbc:o Racle:thin: @hostname:p ort number:databasename
DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port /databasename
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname:port number/databasename

All highlighted parts in the URL format are static and need to be changed only to the remaining parts according to the database settings.

Create Connection object: User name and password using database URL:
The following three forms of the Drivermanager.getconnection () method create a Connection object. Getconnection () The most common form requires passing a database URL, username username and password Password:

Value for partial databasename of the URL database: Assuming you are using an Oracle thin driver, you need to specify a host: port.

Suppose a host TCP/IP address 192.0.0.1 and host name and Oracle Listener are configured to be on port 1521, the database name is EMP, and then the complete database URL is:

Jdbc:oracle:thin: @amrood: 1521:emp

Now you must invoke the appropriate username and password and the getconnection () method to get a connection object, as follows:

String URL = "Jdbc:oracle:thin: @amrood: 1521:emp";
String USER = "username";
String pass = "password"
Connection conn = drivermanager.getconnection (URL, USER, pass);

Use only one database URL:
The second form of the Drivermanager.getconnection () method requires only one database URL:

Drivermanager.getconnection (String URL);

In this case, however, the URL of the database, including the username and password, has the following general form:

Jdbc:oracle:driver:username/password@database

So the above connection can be created as follows:

String URL = "Jdbc:oracle:thin:username/password@amrood:1521:emp";
Connection conn = drivermanager.getconnection (URL);

Use the URL of the database and a Properties object:
The third form of the Drivermanager.getconnection () method requires a database URL and a Properties object:

Drivermanager.getconnection (String URL, Properties info);
Properties object that holds a set of keyword-value pairs. It is used to call the Getconnection () method when the driver property is passed to the driver.

To make the same connection as in the previous example, use the following code:

Import java.util.*;

String URL = "Jdbc:oracle:thin: @amrood: 1521:emp";
Properties Info = new properties ();
Info.put ("User", "username");
Info.put ("Password", "password");

Connection conn = drivermanager.getconnection (URL, info);

To turn off the JDBC Connection:
At the end of the JDBC program, it explicitly requires that all connections to the database be closed to end each database session. However, if you forget that the Java garbage collector closes the connection, it clears the stale object.

Relying on garbage collection, especially in database programming, is a very poor programming habit. You should always turn off the habit of connecting the close () method associated with a connection object.

To ensure that the connection is closed, it can be executed in the finally block in the code. Finally blocks are executed regardless of whether they occur or not.

To turn off the connection above, you should call the close () method, as follows:

Conn.close ();
Explicitly shutting down the connection DBMS saves resources.


To Create a JDBC application:
The following six steps are involved in building a JDBC application:

    1. Import a packet. You need to include packages that contain JDBC classes that require database programming. In most cases, you can use the import java.sql.*.
    2. Registers the JDBC driver. You need to initialize the driver to open a communication channel with the database.
    3. Open the connection. You need to create a connection object using the Drivermanager.getconnection () method, which represents the physical connection to the database.
    4. Execute the query. You need to create and submit an SQL statement to the database using the object declared by the type.
    5. Extracts data from the result set. Requires that you use the appropriate resultset.getxxx () method to retrieve the data for the result set.
    6. Clean up the environment. It is necessary to explicitly shut down all database resources relative to the JVM's garbage collection.

Sample code:
Examples of this example can be used as a template in the need to build JDBC applications.

This sample code has been written based on the installation of the environment and the database in the previous section.

Copy the following example Firstexample.java, compile and run as follows:

Step 1.

Import required packages import java.sql.*; public class Firstexample {//JDBC driver name and database URL static final String jdbc_driver = "Com.mysql.jdbc.Dri 
  Ver ";

  Static final String Db_url = "Jdbc:mysql://localhost/emp";
  The Database credentials static final String USER = "username";
  
  Static final String pass = "password";
  public static void Main (string[] args) {Connection conn = null;
  Statement stmt = null;

   try{//step 2:register JDBC driver Class.forName ("Com.mysql.jdbc.Driver");
   Step 3:open A connection System.out.println ("Connecting to Database ...");

   conn = Drivermanager.getconnection (Db_url,user,pass);
   Step 4:execute a query System.out.println ("creating statement ...");
   stmt = Conn.createstatement ();
   String SQL;
   sql = "SELECT ID, Employees";

   ResultSet rs = stmt.executequery (SQL);
    Step 5:extract data to result set while (Rs.next ()) {//retrieve by column name int id = rs.getint ("id");
     int age = Rs.getint (' age ');
     String a = rs.getstring ("a");

     String last = rs.getstring ("last");
     Display values System.out.print ("ID:" + ID);
     System.out.print (", Age:" + age);
     System.out.print (", A:" + a);
   System.out.println (", Last:" + last);
   }//step 6:clean-up Environment Rs.close ();
   Stmt.close ();
  Conn.close ();
  }catch (SQLException se) {//handle errors for JDBC se.printstacktrace ();
  }catch (Exception e) {//handle errors for class.forname e.printstacktrace ();
   }finally{//finally block used to close resources try{if (stmt!=null) stmt.close ();
   }catch (SQLException se2) {}//Nothing we can do try{if (conn!=null) conn.close ();
   }catch (SQLException se) {se.printstacktrace ();
}//end finally try}//end try System.out.println ("goodbye!");

 }//end Main}//end Firstexample

Now let's compile the example above as follows:

C:>javac Firstexample.java

When you run Firstexample, it produces the following results:

C:>java Firstexample
Connecting to Database ...
Creating Statement
... id:100, Age:18, First:zara, Last:ali id:101, age:25,
First:mahnaz, Last:fatma id:102, age:30, First:zai
D, Last:khan
id:103, age:28, First:sumit, Last:mittal


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.