java連線本機access 資料庫的方法
阿新 • • 發佈:2019-02-01
import java.sql.*;
public class DBconnTest {
public static void main(String args[]) {
//步驟1:載入驅動程式
String sDriver="sun.jdbc.odbc.JdbcOdbcDriver";
try{
Class.forName(sDriver);
}
catch(Exception e){
System.out.println("無法載入驅動程式");
return;
}
System.out.println("步驟1:載入驅動程式——成功!");
Connection dbCon=null;
Statement stmt=null;
String sCon="jdbc:odbc:book";
try{
dbCon=DriverManager.getConnection(sCon);
if(dbCon!=null){
System.out.println("步驟2:連線資料庫——成功!");
}
//步驟3:建立JDBC的Statement物件
stmt=dbCon.createStatement();
if(stmt!=null){
System.out.println("步驟3:建立JDBC的Statement物件——成功!");
}
}
catch(SQLException e){
System.out.println("連線錯誤:"+sCon);
System.out.println(e.getMessage());
if(dbCon!=null){
try{
dbCon.close();
}
catch(SQLException e2){}
}
return;
}
try{//執行資料庫查詢,返回結果
String sSQL="SELECT * "+" FROM bookindex";
ResultSet rs=stmt.executeQuery(sSQL);
while(rs.next()){
System.out.print(rs.getString("BookID")+" ");
System.out.print(rs.getString("BookTitle")+" ");
System.out.print(rs.getString("BookAuthor"));
System.out.println(" " +rs.getFloat("BookPrice"));
}
}
catch(SQLException e){
System.out.println(e.getMessage());
}
finally{
try{
//關閉步驟3所開啟的statement物件
stmt.close();
System.out.println("關閉statement物件");
}
catch(SQLException e){}
try{
//關閉資料庫連線
dbCon.close();
System.out.println("關閉資料庫連線物件");
}
catch(SQLException e){}
}
}
}