考虑与具有默认值的字段的表的默认值,说这样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 {//插入新值}',您能分享一些代码以便我们理解吗? –