Java连接Access
首先安装office2003,就有了Access2003,启动Access,建立新数据库finance.mdb,建表user,包含两个文本型字段username和password,输入测试数据,保存在任意目录下,比如说D盘下。然后打开控制面板 -> 管理工具 -> 数据源 (ODBC),选择"系统DSN",单击“添加”,“完成”,弹出的对话框里将"数据源名"自定义,比如finance。点"选择",找到"D:\finance.mdb"文件,如此一个ODBC数据源就配置好了。
1import java.sql.Connection;
2import java.sql.DriverManager;
3import java.sql.ResultSet;
4import java.sql.SQLException;
5import java.sql.Statement;
6
7public class AccessTest {
8
9 public static void main(String[] args) {
10 Connection conn;
11 Statement stmt;
12 ResultSet rs;
13 try {
14 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
15 } catch (ClassNotFoundException e) {
16 e.printStackTrace();
17 }
18 try {
19 conn = DriverManager.getConnection("jdbc:odbc:finance", "", "");
20 stmt = conn.createStatement();
21 rs = stmt.executeQuery("select * from user");
22 while (rs.next()) {
23 String username = rs.getString(1);
24 String password = rs.getString(2);
25 System.out.println("帐号:" + username);
26 System.out.println("密码:" + password);
27 }
28 conn.close();
29 } catch (SQLException el) {
30 el.printStackTrace();
31 }
32 }
33
34}
35
2import java.sql.DriverManager;
3import java.sql.ResultSet;
4import java.sql.SQLException;
5import java.sql.Statement;
6
7public class AccessTest {
8
9 public static void main(String[] args) {
10 Connection conn;
11 Statement stmt;
12 ResultSet rs;
13 try {
14 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
15 } catch (ClassNotFoundException e) {
16 e.printStackTrace();
17 }
18 try {
19 conn = DriverManager.getConnection("jdbc:odbc:finance", "", "");
20 stmt = conn.createStatement();
21 rs = stmt.executeQuery("select * from user");
22 while (rs.next()) {
23 String username = rs.getString(1);
24 String password = rs.getString(2);
25 System.out.println("帐号:" + username);
26 System.out.println("密码:" + password);
27 }
28 conn.close();
29 } catch (SQLException el) {
30 el.printStackTrace();
31 }
32 }
33
34}
35