【发布时间】:2020-07-10 00:56:43
【问题描述】:
我有一个 SQLLITE 数据库
String query = "CREATE TABLE IF NOT EXISTS plottokens (uuid TEXT PRIMARY KEY NOT NULL, plot INTEGER DEFAULT 0, autoplot INTEGER DEFAULT 0, addon INTEGER DEFAULT 0, combination INTEGER DEFAULT 0, roadcombination INTEGER DEFAULT 0)";
我正在尝试运行
TokenDatabase service = TokenDatabase.getInstance();
Connection connection = service.getConnection();
String query = String.format("INSERT INTO plottokens (`uuid`, `%s`) VALUES (?, 1) ON DUPLICATE KEY UPDATE `uuid`=?, `%s`=`%s`+1", tokenType, tokenType, tokenType);
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, uuid.toString());
preparedStatement.setString(2, uuid.toString());
preparedStatement.executeUpdate();
其中tokenType 是一组预定义的字符串之一,例如“plot”。
这给了我org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (near "DUPLICATE": syntax error)
预期的功能是插入 uuid,如果 uuid 不存在则值为 1,否则将指定列增加 1。
我该如何解决这个问题?
【问题讨论】:
-
on duplicate key update是 MySQL 语法,而不是 SQLite 语法。 -
您想要 sqlite(和 postgres)调用的 upsert,假设您使用的版本足够新以支持该语法(3.24 或更高版本)。