ODBC DataSource添加Access資料庫 Java JDBC訪問Access資料庫 以下為封裝好的DBApplication類 ...
ODBC DataSource添加Access資料庫
- 進入Control Panel->System and Security->Administrative Tools->ODBC Data Sources (64-bit)(根據訪問資料庫的application位數版本決定使用多少位版本數據源)
- 在System DSN(Data Source Name)下添加,選擇Microsoft Access Driver,填寫DataSource Name,Select一個Access資料庫,OK確定即可。也可以點擊Advanced設置login name和password,也可以不設置
Java JDBC訪問Access資料庫
以下為封裝好的DBApplication類
public class DBApplication{ public Connection conn = null; public ResultSet rs = null; private String databaseDriver = "sun.jdbc.odbc.JdbcOdbcDriver"; private String databaseConnStr = "jdbc:odbc:DS"; //註意連接字元串最後部分應該為之前設置的DataSource Name而不是Database Name private String userName = "tianzhi"; //如果之前沒有設置用戶名和密碼就為空 private String passWord = "***"; public DBApplication(){
try{ Class.forName(databaseDriver); } catch(java.lang.ClassNotFoundException e){ System.err.println("載入驅動器有錯誤:" + e.getMessage()); } } public int executeInsert(String sql){ int num = 0; try{ conn = DriverManager.getConnection(databaseConnStr,userName, passWord); Statement stmt = conn.createStatement(); num = stmt.executeUpdate(sql); } catch(SQLException ex){ System.err.println("執行插入有錯誤:" + ex.getMessage()); } closeDataBase(); return num; } public ResultSet executeQuery(String sql){ rs = null; try{ conn = DriverManager.getConnection(databaseConnStr,userName, passWord); Statement stmt = conn.createStatement(); rs = stmt.executeQuery(sql); } catch(SQLException ex){ System.err.println("執行查詢有錯誤:" + ex.getMessage() + sql); } return rs; } public int executeDelete(String sql) { int num = 0; try{ conn = DriverManager.getConnection(databaseConnStr,userName, passWord); Statement stmt = conn.createStatement(); num = stmt.executeUpdate(sql); } catch(SQLException ex){ System.err.println("執行刪除有錯誤:" + ex.getMessage()); } closeDataBase(); return num; } public void closeDataBase(){ try{ conn.close(); } catch(Exception end){ System.err.println("執行關閉Connection對象有錯誤:" + end.getMessage()); } } }