小伙伴问到一个问题,为啥在项目中调用插入或者更新语句时超长的字无法自动截断,而在navicat中直接执行是可以自动截断的?本文主要介绍了mysql超长自动截断实例详解的相关资料,这里通过实例来说明如何实现自动截断的功能,需要的朋友可以参考下,希望能帮助到大家。
如下
create table `p_app_station` (
`wx_app_id` varchar(20) not null,
`app_secret` varchar(33) default null,
`is_binding` int(1) default '0',
`account_id` int(13) default null,
`token` varchar(40) default null,
`bind_url` varchar(200) default null,
`wx_app_name` varchar(50) default null,
`wx_app_sid` varchar(50) default null,
`wx_no` varchar(50) default null,
`create_user_id` varchar(13) default null,
`update_date` datetime default null,
`create_date` datetime default null,
`update_user_id` varchar(13) default null,
`station_type` int(1) unsigned zerofill default null comment '标记类型(试用版:0,会员版:1,定制版:2)',
`active_date` datetime default null comment '使用时间截止',
`app_module_id` varchar(60) default null comment '推送模版消息id',
primary key (`wx_app_id`)
) engine=innodb default charset=utf8
insert into p_app_station(wx_app_id) values('12121312312312啊啊啊啊啊aassasdasd');
select * from p_app_station where wx_app_id like '12121312312312%';
很明显varchar(20) 不足以容纳12121312312312啊啊啊啊啊aassasdasd
查询结果如下
确实自动截断了,但是在项目中执行同样的sql发现并非如此,反而报错。
data truncated for column '%s' at row %ld
考虑到是同一个数据库,不存在模式不同,那么可能性应该出现在jdbcdriver上。
查看jdbc源码
private void setupserverfortruncationchecks() throws sqlexception {
if (getjdbccomplianttruncation()) {
if (versionmeetsminimum(5, 0, 2)) {
string currentsqlmode = this.servervariables.get("sql_mode");
boolean stricttranstablesisset = stringutils.indexofignorecase(currentsqlmode, "strict_trans_tables") != -1;
if (currentsqlmode == null || currentsqlmode.length() == 0 || !stricttranstablesisset) {
stringbuilder commandbuf = new stringbuilder("set sql_mode='");
if (currentsqlmode != null && currentsqlmode.length() > 0) {
commandbuf.append(currentsqlmode);
commandbuf.append(",");
}
commandbuf.append("strict_trans_tables'");
execsql(null, commandbuf.tostring(), -1, null, default_result_set_type, default_result_set_concurrency, false, this.database, null, false);
setjdbccomplianttruncation(false); // server's handling this for us now
} else if (stricttranstablesisset) {
// we didn't set it, but someone did, so we piggy back on it
setjdbccomplianttruncation(false); // server's handling this for us now
}
}
}
}
查看getjdbccomplianttruncation方法,其默认值为
private booleanconnectionproperty jdbccomplianttruncation = new booleanconnectionproperty("jdbccomplianttruncation", true,
messages.getstring("connectionproperties.jdbccomplianttruncation"), "3.1.2", misc_category, integer.min_value);
因此从3.1.2版本在jdbcurl中如果没有设置jdbccomplianttruncation那么默认将会执行不截断并且报错。
那么加上参数是否可以呢?
取舍一下:
如果截断当出现比超长可能会有精度丢失的风险。
因此建议还是在程序中检查。
目前正在做关于使用hibernate validate的相关。
相关推荐:
php中文字符串截断无乱码解决方法
mssql数据库中text类型字段在php中被截断之解
python中的分片与截断序列
以上就是关于mysql超长自动截断实例详解的详细内容。