gpt4 book ai didi

java - 无法在sqlite数据库查询(JAVA)中使用输入作为参数

转载 作者:行者123 更新时间:2023-12-02 03:43:16 25 4
gpt4 key购买 nike

我会尝试更好地解释我的标题,但首先介绍一下我在这里尝试做的事情的背景。我正在开发一款游戏,我需要在本地数据库中搜索用户向程序提供的单词。这样做是为了验证用户实际上使用了符合游戏规则的单词。在这段代码中,我想搜索国家/地区数据库,以验证用户是否确实为游戏指定了国家/地区,而不是随机单词。

由于我对 java 相当陌生,并且刚刚开始了解 SQLite 和 JDBC,因此我在互联网上搜索了如何查询数据库,并发现了一些有用的代码,我根据自己的喜好进行了调整。现在的问题是,从一开始,主方法就会建立到数据库的连接,并从数据库中挑选出每一个东西。这并不是我的本意,所以我想我可以要求用户提供一些输入,将其存储在一个字符串中(在“word”下面),然后使用 SQL 命令 SELECT * FROM [table] WHERE [column] LIKE [条件]

当我将新创建的字符串“word”作为条件并尝试搜索数据库时,程序似乎无法识别单词的含义,甚至根本无法使用它。 Intellij 将“单词”标记为灰色,因此据说它从未被使用过。

为什么 .executeQuery(SQL-command) 无法识别它应该使用单词作为参数?我怎样才能做到这一点,以便用户可以决定要搜索的内容,而无需自己显式键入 SQL 命令?

代码:

package SQL;

//STEP 1. Import required packages
import javax.swing.*;
import java.sql.*;

public class SQLTests {

public static void main(String[] args) throws Exception {
String word = JOptionPane.showInputDialog(null, "Input Country name:",
"Country search", 1);
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager.getConnection("jdbc:sqlite:countries.db");
Statement stat = connection.createStatement();


ResultSet rs = stat.executeQuery("select * from Country where name like word;");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
rs.close();
connection.close();
}
}

最佳答案

不要使用Statement,而是使用PreparedStatement

PreparedStatement stat = connection.prepareStatement("select * from Country
where name like ?");
stat.setString(1, word);
ResultSet rs = stat.executeQuery();

另请检查Difference Between Statement and PreparedStatement

希望它能成功。

关于java - 无法在sqlite数据库查询(JAVA)中使用输入作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36594007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com