java.sql.SQLException: Incorrect string value: '\xD3\xC3JDBC...' for column 'resume' at row 1
产生这种异常的原因在于,mysql中的utf8编码最多会用3个字节存储一个字符,如果一个字符的utf8编码占用4个字节(最常见的就是ios中的emoji表情字符),那么在写入数据库时就会报错。
mysql从5.5.3版本开始,才支持4字节的utf8编码,编码名称为utf8mb4(mb4的意思是max bytes 4),这种编码方式最多用4个字节存储一个字符。
1-可以把MySQL的编码改成
utf8mb4。然后进行简单的配置。解决Connection连接对象的编码问题。如下:
conn.createStatement().execute("SET names 'utf8mb4'");
2-可以改下使用的方法,用setCharacterStream()这个方法就可以。
以下是API中
setCharacterStream()方法,读取字符数
![](https://i-blog.csdnimg.cn/blog_migrate/bad79be6bc35308c67baf8acf513e3fc.png)
而这个是
setAsciiStream()方法,读取字节数
![](https://i-blog.csdnimg.cn/blog_migrate/96eb151dd565ff2cd56d7c54fae94d72.png)
public void ClobUpdate() throws Exception {
Connection conn =JDBCUtil.getConnection();
String sql = "insert into t_clob(resume) values(?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
File file = new File("notes.txt");
InputStream in = new FileInputStream(file);
//Reader r = new FileReader(file);
pstmt.setAsciiStream(1, in,file.length());
//pstmt.setCharacterStream(1, r,(int)file.length());
pstmt.executeUpdate();
JDBCUtil.ReleaseSource(null, pstmt, conn);
}
以下是进行修改后的:
public void ClobUpdate() throws Exception {
Connection conn =JDBCUtil.getConnection();
String sql = "insert into t_clob(resume) values(?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
File file = new File("notes.txt");
//InputStream in = new FileInputStream(file);
Reader r = new FileReader(file);
//pstmt.setAsciiStream(1, in,file.length());
pstmt.setCharacterStream(1, r,(int)file.length());
pstmt.executeUpdate();
JDBCUtil.ReleaseSource(null, pstmt, conn);
}
因为自己可能理解的不是太深刻,但是通过写博客给了自己一种动力去多考虑一些。有没有人看到不重要,但是这里记录着我成长的点滴,珍惜也感恩这个平台,希望以后写的博客越来越有水平。