从java sqlite中的表中删除前k个条目

时间:2014-11-18 20:20:59

标签: java sqlite

我试图使用以下代码从我的sqlite数据库中过期旧条目(这是scala,但与java代码非常相似):

  val c = DriverManager.getConnection(
    s"jdbc:sqlite:my_data.db")
  c.setAutoCommit(false)

  val deleteQuery = c.prepareStatement(
    """delete from my_table
      | where id != ?
      | order by id
      | limit ?
      | """.stripMargin)
  deleteQuery.setInt(1, specialId)
  deleteQuery.setInt(2, maxNumRecords / 2)
  logger.info(s"executing delete query: $deleteQuery")
  val dr = deleteQuery.executeUpdate()
  deleteQuery.close()
  logger.info(s"finished executing delete query: $dr $deleteQuery")

  logger.info("committing db queries")
  c.commit()
  logger.info("finished committing db queries")
  c.close()

但是,我在致电prepareStatement时收到以下异常:

java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (near "order": syntax error)
    at org.sqlite.core.DB.newSQLException(DB.java:890)
    at org.sqlite.core.DB.newSQLException(DB.java:901)
    at org.sqlite.core.DB.throwex(DB.java:868)
    at org.sqlite.core.NativeDB.prepare(Native Method)
    at org.sqlite.core.DB.prepare(DB.java:211)
    at org.sqlite.core.CorePreparedStatement.<init>(CorePreparedStatement.java:40)
    at org.sqlite.jdbc3.JDBC3PreparedStatement.<init>(JDBC3PreparedStatement.java:29)
    at org.sqlite.jdbc4.JDBC4PreparedStatement.<init>(JDBC4PreparedStatement.java:18)
    at org.sqlite.jdbc4.JDBC4Connection.prepareStatement(JDBC4Connection.java:47)
    at org.sqlite.jdbc3.JDBC3Connection.prepareStatement(JDBC3Connection.java:251)
    at org.sqlite.jdbc3.JDBC3Connection.prepareStatement(JDBC3Connection.java:223)

也许我错过了一些简单的东西,但在sqlite3命令行中运行它似乎有效:

sqlite> select id from my_table limit 20;
1
2
3
...
sqlite> delete from my_table where id != 2 order by id limit 5;
sqlite> select id from my_table limit 20;
2
6
7
...

有谁知道可能是什么问题?

1 个答案:

答案 0 :(得分:1)

DELETE的ORDER BY是not enabled by default

您始终可以使用子查询确定要删除的行:

DELETE FROM my_table
WHERE id IN (SELECT id
             FROM my_table
             WHERE id != ?
             ORDER BY id
             LIMIT ?)