วันอังคารที่ 28 มิถุนายน พ.ศ. 2554

การ Connect Oracle JDBC โดยใช้ Java




import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;

public class JDBCDriverOracle {

      public static void main(String[] args) throws Exception {
            System.out.println("Getting Column Names  ");
            Connection con = null;
            String url = "jdbc:oracle:thin:@192.163.1.14:1521:TEST01";
            String driver = "oracle.jdbc.driver.OracleDriver";
            String user = "user1234";
            String pass = "password1234";
            try {
                  Class.forName(driver);
                  con = DriverManager.getConnection(url, user, pass);
                  if (con != null) {
                        System.out.println("Got Connection.");
                        DatabaseMetaData meta = con.getMetaData();
                        System.out.println("Driver Name : " + meta.getDriverName());
                        System.out.println("Driver Version : " + meta.getDriverVersion());
                        System.out.println("Got Connection success....");
                  } else {
                        System.out.println("Could not Get Connection");
                  }
            } catch (Exception e) {
                  e.printStackTrace();
            } finally {
                  if (con != null) {
                        con.close();
                  }
            }
      }

}

Output
Getting Column Names 
Got Connection.
Driver Name : Oracle JDBC driver
Driver Version : 8.1.7.0.0
Got Connection success....

** ปล.อย่าลืม ต้องไปหา Library ชือว่า classes12.jar ด้วยนะครับ