gpt4 book ai didi

java - 使用 latin-1 编码插入数据

转载 作者:行者123 更新时间:2023-12-01 14:03:38 25 4
gpt4 key购买 nike

我需要将编码为 latin-1 的数据插入到 SQLite 数据库中。 (这是一个外部要求;更改数据库或编码不是一个选项。)根据SQLite documentation这应该是可能的:

SQLite is not particular about the text it receives and is more than happy to process text strings that are not normalized or even well-formed UTF-8 or UTF-16. Thus, programmers who want to store IS08859 data can do so using the UTF-8 interfaces.

我可以很容易地对文本进行编码:

Charset charset = Charset.forName("ISO-8859-1");
byte[] data = mystring.getBytes(charset);

但我不知道如何插入它,因为 Statement.executeUpdate 需要一个字符串,而不是字节数组。

最佳答案

虽然您可以假装 ISO8859-1 字符串是 UTF-8 字符串,但最好将它们存储为 blob。SQLite 会在需要时自动在 blob 和字符串之间进行转换(无论如何内部实现都是相同的),并且大多数 internal functions ,当在 blob 而不是字符串上执行时,将使用字节索引,这正是您想要的。

Blob 使用参数处理:

PreparedStatement ps = conn.prepareStatement(
"INSERT INTO MyTable(Name) VALUES(?)");
ps.setBytes(1, data);
ps.execute();

关于java - 使用 latin-1 编码插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19119162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com