以下是最基本使用情況,僅供參考:
packagecom;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.sql.Statement;
/**
*定義數據類連接數據庫且查詢信息
*@authorBR
*@date2015-08-13
*@version1.o
*/
publicclassdataBase{
publicstaticvoidmain(String[]args){
Connectionconnection=null;
try{
//加載驅動
Class.forName("oracle.jdbc.driver.OracleDriver");
//獲取數據庫連接
connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","scott");
//查詢語句
Stringsql="select*fromdept";
//創建Statement對象
Statementstatement=connection.createStatement();
ResultSetrSet=statement.executeQuery(sql);
//判斷查詢的結果集是否為空
if(rSet!=null){
while(rSet.next()){
intnum=rSet.getInt("deptNo");
Stringname=rSet.getString("dName");
Stringloc=rSet.getString(3);
System.out.println(num+"\t"+name+"\t"+loc);
}
}
//關閉資源
rSet.close();
statement.close();
connection.close();
}catch(ClassNotFoundExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(SQLExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}