デフォルト値を持つフィールドを持つテーブルを考えると、ここsomething
のように言う:のMySQL: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:あなたは精巧にできますか? –
私は 'if(){//デフォルトを使う} else {//新しい値を挿入}'を意味するので、理解できるようにいくつかのコードを教えていただけますか? –