MySQL from Java: Inserting a default value using a PreparedStatement INSERT query parameter

时间:2017-06-19 13:55:41

标签: java mysql

Given a table with a field which has a default value, say like something here:

CREATE TABLE foo (
    time DATETIME PRIMARY KEY,
    something CHAR (16) DEFAULT 'a default',
);

... and a prepared statement like this:

INSERT INTO foo (time, something) VALUES (?, ?)

How does one then opt to insert the default value of something?

I know I can get it by omitting the field. However in my case I want to, in the same query, set the value in some records, and defer to the database to insert whatever is configured as the the default value in others.

Here's an example code snippet:

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();

I've Googled and checked the documentation here, without finding anything which answers this specifically for MySQL:

https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference.html

2 个答案:

答案 0 :(得分:0)

一个可行的解决方案似乎是构造查询以使用MySQL COALESCE()DEFAULT()函数将空值映射到默认值。因此,重写示例插入查询,如下所示:

INSERT INTO foo (time, something) VALUES (?, COALESCE(?, DEFAULT(something)))

然后,如果我们在第二个参数中插入null,它将改为插入默认值(当然,也可以为null):

// ...
    for(Field field : Field.values()) {
        if (field.parseIndex >= loggedSensors.length) {
            // MySQL permits setting null like this, other DBs may
            // require #setNull(int, int)
            stmt.setObject(field.ordinal()+1, null); 
        else
            stmt.setObject(
                field.ordinal()+1, 
                field.parse(loggedSensors[field.parseIndex]));
    }
// ...

可以根据需要推广多个字段。虽然请注意,DEFAULT() 内部的字段必须已定义默认值,否则即使未使用默认值也会出错。

答案 1 :(得分:-1)

Don't specify the field in the INSERT statment and the default value will be used.

INSERT into foo (time) VALUES (?);