首先,您需要下载 ucanaccess 和其他随附的 jar 文件并将其包含到您的 Java 项目 here's how you can do it。
现在假设您有一个名为 UserLoginDB.accdb 的 MS Access 数据库,它(为简单起见)包含一个名为 UsersTable 的数据表,其中包含 3 个名为的特定列, ID(自动编号)、LoginName(文本)和密码(文本)。将一些虚构数据添加到此 MS Access DB 表中,以便可以从您的 Java 应用程序中检索此 db 数据。确保您的用户表中的一条记录包含此数据(用于演示目的):
LoginName: Fred Flintstone
Password: 123456
关闭您的 MS Access 数据库。
现在,给定密码字符串 "123456",我们将访问名为 UserLoginDB.accdb 的 MS Access 数据库并获取该数据库的所有者 (LoginName) UserTable 中包含的密码。在您的 Java 应用程序中的某处(按钮事件或其他)粘贴以下代码:
String nl = System.lineSeparator();
String dbPath = "";
// Navigate and select the MS Access database file:
javax.swing.JFileChooser fileChooser = new javax.swing.JFileChooser(new File(".").getAbsolutePath());
javax.swing.filechooser.FileFilter filter =
new javax.swing.filechooser.FileNameExtensionFilter("MS Access Database",
"mdb", "mde", "accdb", "accde", "accdw");
fileChooser.setFileFilter(filter);
int returnVal = fileChooser.showOpenDialog(this); //(Component) evt.getSource());
if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (!file.exists()) {
throw new IllegalArgumentException(nl + "File Selection Error!" + nl
+ "The Database file can not be found at the supplied path:" + nl
+ "(" + file.toString() + ")." + nl);
}
String ext = file.getName().substring(file.getName().lastIndexOf("."));
if (!ext.equalsIgnoreCase(".mdb") && !ext.equalsIgnoreCase(".accdb")
&& !ext.equals(".accdw") && !ext.equals(".accde") && !ext.equals(".mde")) {
throw new IllegalArgumentException(nl + "File Selection Error!" + nl
+ "The Database file selected is not a Microsoft Access Database file: "
+ "(" + file.getName() + ")." + nl);
}
try {
dbPath = file.getCanonicalPath();
}
catch (IOException ex) {
System.err.println(ex);
}
}
String userName = "";
String password = "";
String dbURL = "";
java.sql.Connection conn = null;
try {
dbURL = "jdbc:ucanaccess://" + dbPath + ";memory=false";
conn = java.sql.DriverManager.getConnection(dbURL, userName, password);
String sql = "SELECT LoginName FROM "
+ "UsersTable WHERE Password = ?;";
try (java.sql.PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, "123456");
try (java.sql.ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("LoginName"));
}
}
}
conn.close();
}
catch (java.sql.SQLException ex) {
System.err.println(ex);
}
上面的代码允许您浏览本地文件系统,以便您可以找到创建 UserLoginDB.accdb 数据库文件的位置并选择它。选择文件对话框的 Open 按钮后,将访问 MS Access 数据库并查询用户表以获取密码 123456 和名称 Fred FlintStone(相关到这个密码)将被打印到控制台窗口中。