考慮與具有默認值的字段的表的默認值,說這樣something
這裏:的MySQL從Java:插入使用PreparedStatement INSERT查詢參數
CREATE TABLE foo (
time DATETIME PRIMARY KEY,
something CHAR (16) DEFAULT 'a default',
);
......像這樣一個準備好的聲明:
INSERT INTO foo (time, something) VALUES (?, ?)
那麼如何選擇插入缺省值something
?
我知道我可以通過忽略該字段來獲得它。但在我的情況下,我想在同一個查詢中,在一些記錄中設置值,並按照數據庫插入任何配置爲其他值的默認值。
下面是一個示例代碼片段:
String sql = "INSERT INTO foo (time, s1, s2, s3, ...) VALUES (?, ?, ?, ?, ...)";
// Many fields. You get the picture.
PreparedStatement stmt = connection.prepareStatement(sql);
connection.setAutoCommit(false);
// Insert the lines. The number of fields can change from one line to
// the next, depending on the sensors fitted at the time. The mapping
// of fields -> database values is defined by the enum Fields.
Field badField = null;
try {
for(String line: loglines) {
String loggedSensors[] = line.toString().split (",");
for(Field field : Field.values()) {
if (field.parseIndex >= loggedSensors.length) {
log.warning("using default value for absent field" +
field.columnName);
// Omitting the field generates an error.
// How do we set the field to a default here?
continue;
}
badField = field;
stmt.setObject(
field.ordinal()+1,
field.parse(loggedSensors[field.parseIndex]));
}
stmt.addBatch();
stmt.executeBatch();
}
} catch (Exception e) {
log.error("error inserting field "+badField, e);
return;
}
connection.commit();
我GOOGLE了,在這裏檢查的文件,沒有找到任何事情專門回答了這個爲MySQL:
https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference.html
爲什麼你不使用條件? –
@YCF_L:你能詳細說明一下嗎? –
我的意思是如果(){//使用默認值} else {//插入新值}',您能分享一些代碼以便我們理解嗎? –