从Ucanaccess中的单个单元格获取字符串(Java)

huangapple go评论131阅读模式
英文:

Get String from a single cell in Ucanaccess (Java)

问题

我正在使用Ucanaccess进行高中项目,我需要从Access数据库中的单个单元格获取一个字符串。我已经进行了调查,但似乎唯一可用的选项是使用connection.getString(int),但那只会获取整行数据。

英文:

I'm using Ucanaccess for a highschool project, and I need to get a String from a single cell in Access. I have investigated, but the only option that seems to be available is to use connection.getString(int), but that only gets the whole row.

答案1

得分: 1

首先,您需要下载并将ucanaccess以及其他相关的jar文件添加到您的Java项目中,具体操作可以参考这个链接

假设您有一个名为UserLoginDB.accdb的MS Access数据库,其中(为简单起见)包含一个名为UsersTable的数据表,该表包含3个特定的列,分别是ID(AutoNumber)、LoginName(Text)和Password(Text)。向这个MS Access数据库表中添加一些虚构的数据,以便可以从您的Java应用程序中检索这些数据库数据。确保您的用户表中有一条包含以下数据的记录(用于演示目的):

LoginName:    Fred Flintstone
Password:     123456

关闭您的MS Access数据库。

现在,假设给定密码字符串为**"123456",我们将访问名为UserLoginDB.accdb**的MS Access数据库,并获取包含在UserTable中的该密码的所有者(LoginName)。在您的Java应用程序的某个地方(例如按钮事件或其他位置),粘贴以下代码:

String nl = System.lineSeparator();
String dbPath = "";

// 导航并选择MS Access数据库文件:
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数据库文件并选择它。一旦选择了文件对话框中的<kbd>Open</kbd>按钮,MS Access数据库将被访问,并且将查询UsersTable以获取密码123456,并将与该密码相关联的名称Fred FlintStone打印到控制台窗口中。

英文:

First you need to download and include the ucanaccess and other accompanying jar files to your Java Project here's how you can do it.

Now let's say you have an MS Access database named UserLoginDB.accdb which (for simplicity) contains a single data table named UsersTable which consists of 3 specific columns named, ID (AutoNumber), LoginName (Text), and Password (Text). Add some fictitious data into this MS Access DB table so that this db data can be retrieved from your Java Application. Make sure one of the records in your Users Table contains this data (for demo purposes):

       LoginName:    Fred Flintstone
Password:     123456

Close your MS Access database.

Now, given the password string of "123456" we're going to access the MS Access Database named UserLoginDB.accdb and acquire the owner (LoginName) of that password contained within the UserTable. Somewhere in your Java application (a button event or whatever) paste the following code:

String nl = System.lineSeparator();
String dbPath = &quot;&quot;;
// Navigate and select the MS Access database file:
javax.swing.JFileChooser fileChooser = new javax.swing.JFileChooser(new File(&quot;.&quot;).getAbsolutePath());
javax.swing.filechooser.FileFilter filter = 
new javax.swing.filechooser.FileNameExtensionFilter(&quot;MS Access Database&quot;, 
&quot;mdb&quot;, &quot;mde&quot;, &quot;accdb&quot;, &quot;accde&quot;, &quot;accdw&quot;);
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 + &quot;File Selection Error!&quot; + nl
+ &quot;The Database file can not be found at the supplied path:&quot; + nl
+ &quot;(&quot; + file.toString() + &quot;).&quot; + nl);
}
String ext = file.getName().substring(file.getName().lastIndexOf(&quot;.&quot;));
if (!ext.equalsIgnoreCase(&quot;.mdb&quot;) &amp;&amp; !ext.equalsIgnoreCase(&quot;.accdb&quot;)
&amp;&amp; !ext.equals(&quot;.accdw&quot;) &amp;&amp; !ext.equals(&quot;.accde&quot;) &amp;&amp; !ext.equals(&quot;.mde&quot;)) {
throw new IllegalArgumentException(nl + &quot;File Selection Error!&quot; + nl
+ &quot;The Database file selected is not a Microsoft Access Database file: &quot;
+ &quot;(&quot; + file.getName() + &quot;).&quot; + nl);
}
try {
dbPath = file.getCanonicalPath();
}
catch (IOException ex) {
System.err.println(ex);
}
}
String userName = &quot;&quot;;
String password = &quot;&quot;;
String dbURL = &quot;&quot;;
java.sql.Connection conn = null;
try {
dbURL = &quot;jdbc:ucanaccess://&quot; + dbPath + &quot;;memory=false&quot;;
conn = java.sql.DriverManager.getConnection(dbURL, userName, password); 
String sql = &quot;SELECT LoginName FROM &quot;
+ &quot;UsersTable WHERE Password = ?;&quot;;
try (java.sql.PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, &quot;123456&quot;);
try (java.sql.ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString(&quot;LoginName&quot;));
}
}
}
conn.close();
}
catch (java.sql.SQLException ex) {
System.err.println(ex);
}

The above code allows you to navigate your local file system so that you can find where you created your UserLoginDB.accdb database file and select it. Once the file dialog's <kbd>Open</kbd> button is selected then MS Access Database will accessed and the UsersTable queried for the Password 123456 and the name Fred FlintStone (related to this password) will be printed into the Console Window.

huangapple
  • 本文由 发表于 2020年10月16日 02:52:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64378011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定