简体   繁体   English

将中文字符串作为UTF-8插入MySQL LongBlob列

[英]Insert Chinese Character String into MySQL LongBlob column as UTF-8

By doing this: 通过做这个:

File file1 = new File("/usr/local/test/multipartMimeMsg.txt");
            FileOutputStream fos1 = new FileOutputStream(file1);
            String s = byteArrayToHexString(multipartMimeMsg.getBytes());
            fos1.write(s.getBytes(), 0, s.getBytes().length);

I verified that my multipartMimeMsg string can see the hexa representation of the chinese characters. 我验证了我的multipartMimeMsg字符串可以看到汉字的十六进制表示形式。 I then proceed to do this: 然后,我继续执行此操作:

prepstmt.setObject(2, multipartMimeMsg );

But it turns up as ??? 但是它变成??? or 3F3F3F in hexa representation. 或以十六进制表示的3F3F3F。 It should show E4BDA0E5A5BDE59097 Am I missing something? 它应该显示E4BDA0E5A5BDE59097我缺少什么吗? I have set my Table Options to Charset utf8, Collation to utf8_general_ci. 我已将表选项设置为Charset utf8,将排序规则设置为utf8_general_ci。

Connection string is jdbc:mysql://localhost:3306/test 连接字符串为jdbc:mysql:// localhost:3306 / test

I'm not sure if setObject() can handle LOBs correctly - have you tried this with setBytes() or setBinaryStream() ? 我不确定setObject()可以正确处理LOB-您是否使用setBytes()setBinaryStream()尝试了此操作?

Also, any reason why you're storing text as a BLOB instead of TEXT ? 另外,您为什么将文本存储为BLOB而不是TEXT任何原因?

String s = byteArrayToHexString(multipartMimeMsg.getBytes());

I assume multipartMimeMsg is a string. 我假设multipartMimeMsg是一个字符串。 Look carefully about the getBytes() method in JavaDoc, it will use system default character set(depending on your OS) to encode the string into bytes, which can vary on different systems. 仔细查看JavaDoc中的getBytes()方法,它将使用系统默认字符集(取决于您的OS)将字符串编码为字节,这在不同的系统上可能会有所不同。

The more accurate way is set the exact character set you want, like aString.getBytes("UTF-8"). 更准确的方法是设置所需的确切字符集,例如aString.getBytes(“ UTF-8”)。

And for the column definition problem, I recommend using "TEXT" type, as suggested by @Dmitri. 对于列定义问题,我建议使用@Dmitri建议的“ TEXT”类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM