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)
可能出现什么问题?
答案 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
在语句中分配它们。