close
要從jdbc連到odbc的驅動程式,因為JAVA8已經沒有再支援了,而替代方案有兩個方式,第一個比較呆版就是切回JAVA7,但是有點不實用,畢竟JAVA一直在更新,盡量不要走回頭路,第二個是利用外部函式庫jar檔幫我們完成,可以在Google搜尋UCanAccess-2.0.9.5,把裡面的Jar檔放進涵式庫裡面,就可以使用了~
做法:下載UCanAccess-2.0.9.5壓縮包,解壓後把lib檔裡的jar檔和ucanaccess-2.0.9.5.jar檔放進jdk預設路徑C:\ProgramFiles\Java\jdk1.8.0_161\jre\lib\ext 就可以使用到外部涵式庫了。
有需要涵式庫的可以跟我講,再貼連結~
(A)使用JAVA8加入外部函數庫來連結
import java.sql.*;
public class Access_GetData
{
public static void main(String[] args)
{
Connection dbCon = null;
Statement stmt = null;
ResultSet rs = null;
//程式參數
String sDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
String sCon = "jdbc:odbc:nana";
try{ //載入JDBC driver
Class.forName(sDriver);
}
catch(Exception e){
System.out.println("無法載入驅動程式");
return;
}
try{ //建立資料連結和Statement物件
dbCon = DriverManager.getConnection(sCon);
if(dbCon != null)
System.out.println("建立Connection物件成功!");
stmt = dbCon.createStatement();
if(stmt != null)
System.out.println("建立Statement物件成功!");
}
catch(SQLException e){
System.out.println("與資料來源連結錯誤: " + sCon);
System.out.println(e.getMessage());
if(dbCon != null){
try{ dbCon.close(); }
catch( SQLException e2 ) {}
}
return;
}
try{
rs = stmt.executeQuery("SELECT * FROM employee");
while(rs.next()){
System.out.print(rs.getString(1));
System.out.print("\t");
System.out.print(rs.getString("NAME"));
System.out.print("\t");
System.out.print(rs.getBoolean(3));
System.out.print("\t");
System.out.print(rs.getDate(4));
System.out.print("\t");
System.out.print(rs.getByte("AGE"));
System.out.print("\t");
System.out.println(rs.getString(6));
}
}
catch(SQLException e){}
try{
stmt.close();
dbCon.close();
}
catch( SQLException e ){}
}
}
(B)使用JAVA7來連結
import java.sql.*;
public class Test {
public static void main(String[] args) {
Connection dbCon = null;
Statement stmt = null;
ResultSet rs = null;
//程式參數
String sDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
String sCon = "jdbc:ucanaccess://c:/MyDatabase.accdb";
try //載入JDBC driver
{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
} catch (Exception e) {
System.out.println("無法載入驅動程式");
return;
}
try //建立資料連結和Statement物件
{
dbCon = DriverManager.getConnection(sCon);
if (dbCon != null) {
System.out.println("建立Connection物件成功!");
}
stmt = dbCon.createStatement();
if (stmt != null) {
System.out.println("建立Statement物件成功!");
}
} catch (SQLException e) {
System.out.println("與資料來源連結錯誤: " + sCon);
System.out.println(e.getMessage());
if (dbCon != null) {
try {
dbCon.close();
} catch (SQLException e2) {
}
}
return;
}
try {
rs = stmt.executeQuery("SELECT * FROM employee");
while (rs.next()) {
System.out.print(rs.getString(1));
System.out.print("\t");
System.out.print(rs.getString("NAME"));
System.out.print("\t");
System.out.print(rs.getBoolean(3));
System.out.print("\t");
System.out.print(rs.getDate(4));
System.out.print("\t");
System.out.print(rs.getByte("AGE"));
System.out.print("\t");
System.out.println(rs.getString(6));
}
} catch (SQLException e) {
} finally {
try {
stmt.close();
dbCon.close();
} catch (SQLException e) {
}
}
}
}
結果圖:
文章標籤
全站熱搜
留言列表