如何更新SQLite DB中的值?

时间:2016-04-22 14:23:39

标签: java sqlite jdbc

我正在尝试更新SQLite数据库中的特定行,但它似乎不起作用。这就是数据库的样子。

-----------------------
_id | user | coins
-----------------------
1   | me   | 20
-----------------------

这就是我的代码:

public static void updateUserWallet() throws SQLException {
        try {
            int coins;
            Class.forName("org.sqlite.JDBC");
            Connection connection = DriverManager.getConnection("jdbc:sqlite:Database.db");

            String query = "Select * from userSettings WHERE user = " + "'" + lastUser + "'";
            Statement statement = connection.createStatement();
            ResultSet result = statement.executeQuery(query);

            while (result.next()) {
                coins = result.getInt("coins");
                result.updateInt("coins", 10);
                result.updateRow();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

选择表和东西是有效的,但是第二个我执行这个代码,它崩溃了:

result.updateInt("coins", 10);
result.updateRow();

出现此错误:

java.sql.SQLException: not implemented by SQLite JDBC driver

    at org.sqlite.jdbc4.JDBC4ResultSet.unused(JDBC4ResultSet.java:321)
    at org.sqlite.jdbc4.JDBC4ResultSet.updateInt(JDBC4ResultSet.java:452)
    at dysanix.advanced.kikbot.main.updateUserWallet(main.java:367)
    at dysanix.advanced.kikbot.main$1.cmdGameRoll(main.java:266)
    at dysanix.advanced.kikbot.main$1.run(main.java:142)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown Source)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
-----------------------
_id | user | coins
-----------------------
1   | me   | 20
-----------------------

我想做的就是更新" 20"至" 10" (或其他数字)。 我该如何正确地做到这一点?

1 个答案:

答案 0 :(得分:5)

错误消息告诉您SQLite JDBC驱动程序不支持可更新的ResultSet。 (该功能“未由SQLite JDBC驱动程序实现”。)因此,您需要使用UPDATE语句,如下所示:

String query = "UPDATE userSettings SET coins=? WHERE user=?";
PreparedStatement statement = connection.prepareStatement(query);
statement.setInt(1, 10);
statement.setString(2, lastUser);
statement.executeUpdate();