【发布时间】:2013-02-25 10:32:48
【问题描述】:
我有一张桌子。
mysql> SELECT @@GLOBAL.sql_mode;
...返回空。
mysql> create table testtable ( name varbinary(5));
mysql> insert into testtable values('hellowhowareyoudsafafas');
Query OK, 1 row affected, 1 warning (0.00 sec)
数据被插入到表中。但是如果我使用 c3p0 的 ComboPoolDataSource,我会得到异常 com.mysql.jdbc.MysqlDataTruncation。
由于我没有在 MySQL 5.1 上设置 MySQL 严格模式,我希望数据能够存储在表中。我应该怎么做才能允许通过 c3p0 自动截断。
=====好的我做到了,但是有没有更简洁的方法======
PreparedStatement ps1 = connection.prepareStatement("SELECT @@sql_mode");
ResultSet rs = ps1.executeQuery();
String originalSqlMode = "";
if(rs.next()) {
originalSqlMode = rs.getString(1);
System.out.println(originalSqlMode);
}
String newSqlMode = originalSqlMode.replace("STRICT_ALL_TABLES", "").replace("STRICT_TRANS_TABLES", "").replace(",,", ",");
ps1 = connection.prepareStatement("SET SESSION sql_mode=?");
ps1.setString(1, newSqlMode);
ps1.execute();
PreparedStatement ps2 = connection.prepareStatement("insert into testtable values (?)");
ps2.setString(1, "indianpeople");
ps2.execute();
【问题讨论】:
-
这是我的一点想法,直到你得到正确的答案......即使在 MySQL 中你也会收到警告。我认为捕获
MysqlDataTruncation相当于Java 忽略警告。