JDBC连接oracle

花了一个下午的时间终于连上了:

总结一下JDBC连接oracle的步骤:

1.Load the Driver
<1.Class.forName()|Class.forname().newinstance()|new DirverName()
<2.实例化时自动向DirverManager注册,不需显式调用DriverManger.registerDriver()方法

2.Connect to the DataBase
<1.DriverManager.getConnection()

3.Execute the SQL
<1.Connection CreateStatement()
<2.Statement.excuteQuery()
<3.Statement.executeUpdate()
4.Retrieve the result data
<1.循环取得结果while(rs.next())
5.Show the result data
<1.将数据库中的各种类型转换为JAVA中的类型(getXXX)方法
6.Close
<1.close the resultset./close the statement/close the connection

 

JDBC连接oracle例子程序:
import java.sql.*;

public class TestJDBC {

public static void main(String[] args) throws Exception {

Class.forName("oracle.jdbc.driver.OracleDriver"); //new Driver向DriverManager注册
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "abc123");
//"jdbc:oracle:thin:@localhost:1521:orcl"为JDBC的连接URL(每种数据库的getConnection()不一样),localhost为本地IP
Statement stmt = conn.createStatement(); //创建statement对象
ResultSet rs = stmt.executeQuery("select * from dept"); //通过Statement执行SQL语句
while(rs.next()){ //对ResultSet进行遍历
System.out.println(rs.getString("deptno"));
System.out.println(rs.getInt("deptno"));
}
rs.close(); //关闭相关对象
stmt.close();
conn.close();

}

}


更加完善的例子程序(异常处理):
import java.sql.*;

public class TestJDBC {

public static void main(String[] args) {
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
//new oracle.jdbc.driver.OracleDriver();另一种new Driver的方式
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "abc123");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from dept");
while(rs.next()) {
System.out.println(rs.getString("deptno"));
System.out.println(rs.getInt("deptno"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

}

JDBC连接oracle,布布扣,bubuko.com

JDBC连接oracle

上一篇:fiddler 在火狐(firefox)下无效的问题 ——Fiddler监听Firefox、Chrome中的http请求


下一篇:HBASE cassandra 本质上其实都是KEY -VALUE 的行式存储数据库。