从UcanaccessJava中的单个单元格获取字符串

问题描述

我正在将ucanaccess用于一个高中项目,我需要从Access中的单个单元格获取一个String。我已经调查过,但是似乎唯一可用的选择是使用connection.getString(int),但这只会得到整行。

解决方法

首先,您需要下载 ucanaccess 并将其他随附的jar文件包含到Java项目here's how you can do it中。

现在,我们假设您有一个名为 UserLoginDB.accdb 的MS Access数据库,该数据库(为简单起见)包含一个名为 UsersTable 的数据表,该数据表由3个特定的列组成, ID (自动编号), LoginName (文本)和密码(文本)。在此MS Access DB表中添加一些虚拟数据,以便可以从Java应用程序中检索该数据库数据。确保“用户表”中的记录之一包含此数据(出于演示目的):

       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 数据库文件的位置并将其选中。选择文件对话框的打开按钮后,将访问MS Access数据库,并在UsersTable中查询密码 123456 和名称 Fred FlintStone (相关密码)将被打印到控制台窗口中。