Access數據庫操作示例
- package test;
- import Java.sql.Connection;
- import Java.sql.DriverManager;
- import Java.sql.ResultSet;
- import Java.sql.Statement;
- /**
- *
- * 連接Access數據庫的簡單示例。
- * 對於Excel可將代碼中的url修改為
- * "jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=workbook.xls"
- * 對於Excel一個Sheet認為一個數據表,查詢語句可寫為"select * from [Sheet1$]"
- *
- */
- public class TestAccess {
- /**
- * 入口
- *
- * @param args
- */
- public static void main(String[] args) {
- try {
- // 注冊數據庫連接驅動
- Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
- // Access數據庫文件路徑
- String dbpath = "D:\\db1.mdb";
- // 連接Access數據庫的url
- String url = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ="
- + dbpath;
- // 創建數據庫連接
- Connection conn = DriverManager.getConnection(url, "", "");
- // 向Access中已存在的數據表test插入一條數據
- String sql = "insert into test(testa, testb) values('abc', 'def')";
- Statement stmt = conn.createStatement();
- stmt.executeUpdate(sql);
- // 查詢Access中數據表test已存在的數據
- sql = "select id, testa, testb from test";
- stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery(sql);
- while (rs.next()) {
- System.out.println(rs.getString(1));
- System.out.println(rs.getString(2));
- System.out.println(rs.getString(3));
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }