First time to create JDBC connection to ORACLE SQL

来源:互联网 发布:free book 知乎 编辑:程序博客网 时间:2024/06/05 23:41

MyEclipse 8.6.1, Oracle 11.1g standard edition, jdk1.6.0_31 are already installed.

1)  Locate the JDBC driver provided by ORACLE under [ORACLE_HOME]\jdbc\lib\ojdbc6.jar or download the drivers from oracle site.

http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-111060-084321.html

2) Read the Readme.txt under [ORACLE_HOME]\jdbc\, we can find some valuable information.

3) Copy ojdbc6.jar to your project lib dir, or add this jar by configuring the build path, adding the external jar file.

4) Compile the source code.


import java.sql.*;

public class JDBCTest {
  public static void main(String args[])
  {
      Connection conn = null;
      // System.setProperty("jdbc.drivers", "oracle.jdbc.driver.OracleDriver");
      
      try
      {
          Class.forName("oracle.jdbc.driver.OracleDriver");
      }
      catch (ClassNotFoundException ex)
      {
          ex.printStackTrace();
      }
      
      
      try
      {
          conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl", "abc", "abc123");
          Statement stat = conn.createStatement();
          stat.executeUpdate("CREATE TABLE Greetings (Message VARCHAR(20))");
          stat.executeUpdate("INSERT INTO Greetings VALUES('Hello world!')");
          ResultSet result = stat.executeQuery("SELECT * FROM Greetings");
          if (result.next())
          {
              System.out.println(result.getString(1));
          }
          result.close();
          stat.executeUpdate("DROP TABLE Greetings");
      }
      catch (SQLException ex)
      {
          for (Throwable t: ex)
          {
              t.printStackTrace();
          }
      }
      finally
      {
          if (conn != null)
          {
              try
              {
                  conn.close();
              }
              catch (SQLException ex)
              {
                  for (Throwable t: ex)
                  {
                      t.printStackTrace();
                  }
              }
          }
      }
  }
}


Tips:

1) Oracle SQL 11g uses ojdbc5.jar or ojdbc6.jar for the driver, ojdbc14.jar is deprecated.

2) Pay attention to the driver path, it is "oracle.jdbc.driver.OracleDriver". Once you navigate the ojdbc6.tar, we will get it.

3) Pay attention to the url part, it is "jdbc:oracle:thin:@127.0.0.1:1521:orcl". The format is like this.

jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=yourhost.yourdomain.com)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=yourservicename)))

how to find your service name ?

Refer to [...]\product\11.1.0\db_1\NETWORK\ADMIN\{listener.ora, tnsnames.ora, sqlnet.ora}

http://www.rojotek.com/blog/2008/01/04/oracle-sid-service_name/
http://www.orafaq.com/wiki/JDBC

4) Read 'Readme.txt' under '[ORACLE_HOME\jdbc\]', it is important.

原创粉丝点击