mysql jdbc:将true值插入位列变为false

时间:2018-01-11 12:50:15

标签: java mysql jdbc

mysql jdbc:将true值插入位列会变为false,但是 命令行客户端工作正常。例如,

员工

+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| id         | varchar(8)  | NO   | PRI | NULL    |       |
| name       | varchar(20) | NO   |     | NULL    |       |
| full_time  | bit(1)      | NO   |     | NULL    |       |
+------------+-------------+------+-----+---------+-------+

命令行:

mysql> insert into Employee (id,name,full_time) values ('100', 'John', true);

mysql> select * from Employee;
+--------+------+-----------+
| id     | name | full_time |
+--------+------+-----------+
| 100    | John |  (symbol) |      
+--------+------+-----------+

mysql> select count(*) from Employee where full_time=true;
+----------+
| count(*) |
+----------+
|        1 |
+----------+
1 row in set (0.00 sec)

作品。

但是JDBC

String sql = "Insert into Employee (id,name,full_time) values (?, ?, ?)";
PreparedStatement s = connection.prepareStatement(sql);
s.setObject(1, "100");
s.setObject(2, "John");
s.setObject(3, true);
s.executeUpdate();

插入了行,但full_time列为false。

mysql> select * from Employee;
+--------+------+-----------+
| id     | name | full_time |
+--------+------+-----------+
| 100    | John |           |      
+--------+------+-----------+


mysql> select count(*) from Employee where full_time=true;
+----------+
| count(*) |
+----------+
|        0 |
+----------+
1 row in set (0.00 sec)

可能出现什么问题?

1 个答案:

答案 0 :(得分:2)

使用setBoolean将真/假值分配到full_time列:

String sql = "Insert into Employee (id, name, full_time) values (?, ?, ?)";
PreparedStatement s = connection.prepareStatement(sql);
s.setString(1, "100");
s.setString(2, "John");
s.setBoolean(3, true);
s.executeUpdate();

始终对要插入/更新的类型使用适当的setter。我不知道s.setObject(1, '100')是如何编译的,但是Java中的字符串文字使用双引号,我们应该使用setString在语句中分配它们。