/* 导入Java类 */
import java.sql.*;
/* 主类 */
public class Stu
{
public static void main(String argv[]) throws SQLException
{
/* 声明并初始化变量 */
String query = new String("SELECT id,name,score FROM student");
String name;
int id,score;
Connection conn=null;
try{
/*第一种注册JDBC的Oracle驱动的方法*/
//Class.forName("oracle.jdbc.driver.OracleDriver");
/*第二种注册JDBC的Oracle驱动的方法*/
DriverManager.registerDriver
(new oracle.jdbc.driver.OracleDriver());
}catch(Exception e){
System.out.println("Could not load drive:"+e);
System.exit(-1);
}
/*利用Thin驱动程序获取Oracle连接*/
//conn=DriverManager.getConnection
("jdbc:oracle:thin:@10.1.14.34:1521:MyDB","test","test");
//System.out.println("Connected with THIN CLIENT!");
/*利用OCI驱动程序获取Oracle连接*/
conn=DriverManager.getConnection
("jdbc:oracle:oci8:@","test","test");
System.out.println("Connected with OCI8!\n");
/* 使用try ... catch抓取并处理例外 */
try {
Statement pstmt=conn.createStatement();
/* 执行SQL语句 */
ResultSet rset= pstmt.executeQuery(query);
/* 循环处理JDBC结果集的数据 */
while(rset.next()) {
id=rset.getInt(1);
name = rset.getString(2);
score=rset.getInt(3);
System.out.println("ID=" + id);
System.out.println("NAME=" + name);
System.out.println("SCORE=" + score);
System.out.println("---------------");
}
/* 关闭JDBC结果集 */
rset.close();
/* 关闭动态SQL语句 */
pstmt.close();
}
catch(SQLException e) {
System.out.println("出现SQL例外:" + e.getMessage());
}
conn.close();
}
}
编译、执行上述源程序,可显示出student表中所有记录。
$javac Stu.java
$java Stu |