在我的java应用程序中,我使用SQLite。 我有62列的表。 这里的代码试图在此表中插入文档。
@Override
protected int insertToDB(Connection connection, String tableName, int pkDocsID, Map < Integer, String > fieldMap) throws SQLException {
PreparedStatement ps = null;
try {
String parametersAsQMarks = DBManager.getInsertParametersAsQMarks(fieldMap.size() + COUNT_RESERVED_FIELDS);
ps = connection.prepareStatement("INSERT INTO " + tableName + " VALUES (" + parametersAsQMarks + ")");
ps.setInt(COUNT_RESERVED_FIELDS, pkDocsID); // reserved field
int step = COUNT_RESERVED_FIELDS + 1;
for (int index = 0; index < fieldMap.size(); index++) {
String fieldValue = fieldMap.get(index + 1);
ps.setString(index + step, fieldValue);
}
return ps.executeUpdate();
} finally {
if (ps != null) {
ps.close();
}
}
}
但我得到错误:
[java] [23.01.2018 20:57:28.312]
md.deeplace.ca.db.SQLiteStrategy.insertM2Document(SQLiteStrategy.java:125) ERROR:
[java] table OUTDocsBS has 62 columns but 37 values were supplied
[java] java.sql.SQLException: table OUTDocsBS has 62 columns but 37 values were supplied
[java] at org.sqlite.DB.throwex(DB.java:288)
[java] at org.sqlite.NestedDB.prepare(NestedDB.java:115)
[java] at org.sqlite.DB.prepare(DB.java:114)
[java] at org.sqlite.PrepStmt.<init>(PrepStmt.java:37)
[java] at org.sqlite.Conn.prepareStatement(Conn.java:231)
[java] at org.sqlite.Conn.prepareStatement(Conn.java:224)
[java] at org.sqlite.Conn.prepareStatement(Conn.java:213)
[java] at com.myproject.ca.db.SQLiteStrategy.insertToDB(SQLiteStrategy.java:64)
我想在填充不是所有列时插入文档。在这种情况下 - 37列。我怎么能这样做?
答案 0 :(得分:2)
您需要为列命名。而不是:
..."INSERT INTO " + tableName + " VALUES (" + parametersAsQMarks + ")");
试
..."INSERT INTO " + tableName + "(columnName1, columnName2, ... columnName37) VALUES (" + parametersAsQMarks + ")");
其中每个命名列与要插入的相应fieldMap
值匹配。根据代码,将fieldMap
更改为Map<String, String>
可能很有用,其中键是列名(而不是列号)。
当然,其他剩余列必须允许为空。