Apr 17, 2008

Java JDBC connect to Oracle database

#將 Oracle Client jdbc\lib\ 底下的 classes12.jar , 複製到 c:\classes12.jar
#Windows 環境變數 CLASSPATH 加入 c:\classes12.jar

import java.sql.*;
public class connDB2 {
public static void main(String[] args)
{
Connection cn = null;
Statement stmt = null;
ResultSet rs= null;
try {
// Load the JDBC driver
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
// Create a connection to the database
String serverName = "192.168.X.X";
String portNumber = "1521";
String sid = "ERP";
String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
String username = "system";
String password = "xxxx";
cn = DriverManager.getConnection(url, username, password);
if (cn == null) System.out.println("connection is null");
stmt = cn.createStatement();
if (cn == stmt) System.out.println("stmt is null");
// query sql statement
rs = stmt.executeQuery("select a from a where rownum <10");
System.out.println("測試資料");
while(rs.next())
{
System.out.println(rs.getString("a"));
}
// delete sql statement
String strSql = "delete from a";
stmt.execute(strSql);
// insert sql statement
strSql = "insert into a values('aaa')";
stmt.execute(strSql);

} catch (ClassNotFoundException cfe) {
// Could not find the database driver
cfe.printStackTrace();
} catch (SQLException sqle) {
sqle.printStackTrace();
// Could not connect to the database
}
catch (Exception e){
e.printStackTrace();
}
finally {
try
{
// System.out.println("out");
stmt.close();
cn.close();
} catch (Exception exception)
{
//exception.printStackTrace();
//System.exit(1);
}
}

}
}

0 意見: