MySQL数据库插入中文时出现Incorrect string value: '\xE6\x97\xB7\xE5\x85\xA8' for column 'sz_name' at row 1

今天在开发时候出现了这个问题

Incorrect string value: '\xE6\x97\xB7\xE5\x85\xA8' for column 'sz_name' at row 1

场景,往MySQL数据库的表中插入中文参数,抛出了这个异常

我用sqlyog执行该段代码时候发现只是出现警告,并没有出现error,但是在代码里面执行抛出了异常,说明管理工具sqlyog对有些约定不是那么严格,而代码中就会报错。提醒自己,以后写sql时候不能忽略管理工具中出现的警告。

解决方案:

在用sql语句建表的时候加入  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci  即可

下面是我的建表语句:

CREATE TABLE `stat_day_exception_201807` (
  `ng_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `ng_report_id` bigint(20) DEFAULT NULL,
  `nt_type` int(11) NOT NULL,
  `sz_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `sz_reason` text COLLATE utf8_unicode_ci,
  `bt_charge` int(11) DEFAULT '0',
  `ts_begin` datetime DEFAULT NULL,
  `ts_end` datetime DEFAULT NULL,
  `bt_attendance` int(11) DEFAULT '0',
  `nt_count` decimal(10,4) NOT NULL DEFAULT '0.0000',
  `nt_minutes` int(11) DEFAULT '0',
  `sz_code` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ng_user_id` bigint(20) DEFAULT NULL,
  `dt_date` datetime DEFAULT NULL,
  PRIMARY KEY (`ng_id`),
  KEY `I_stat_day_exception_sys_user` (`ng_user_id`),
  KEY `I_stat_day_exception_day` (`dt_date`)
) ENGINE=InnoDB AUTO_INCREMENT=1701 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

猜你喜欢

转载自www.cnblogs.com/huangzhang/p/9274401.html