gpt4 book ai didi

java - 如何在 Java 代码创建的 SQL 脚本文件中将 Java byte[] 转换为 MySQL BLOB

转载 作者:行者123 更新时间:2023-11-29 07:37:10 27 4
gpt4 key购买 nike

我有一个 Java 程序可以创建一个 SQL 脚本,该脚本稍后将作为一个文件导入到 MySQL 中。 Java 程序不能直接访问 MySQL 数据库,而是必须生成一个 SQL 文件,其中包含要由 MySQL 摄取的所有插入命令。无需深入了解太多细节,我们可以忽略任何安全问题,因为数据使用一次,然后数据库被删除。

Java 代码做这样的事情:

String sql = "INSERT INTO myTable (column1, column2) VALUES (1, 'hello world');";

BufferedWriter bwr = new BufferedWriter(new FileWriter(new File("output.sql")));
bwr.write(sql);
// then flushes the stream, etc.

我遇到的问题是当我需要将 byte[] 数组作为第三列时:

我遇到的问题是我现在需要包含一个 byte[] 数组作为第三列。因此我想这样做:

byte[] data = getDataFromSomewhere();
// Convert byte[] to String and replace all single quote with an escape character for the import
String dataString = new String(data, StandardCharsets.UTF_8).replaceAll("'", "\\\\'");

String sql = "INSERT INTO myTable (column1, column2, column3) VALUES (1, 'hello world', '" + dataString + "');";

BufferedWriter bwr = new BufferedWriter(new FileWriter(new File("output.sql")));
bwr.write(sql);
// then flushes the stream, etc.

问题是当我加载文件时在另一台计算机上出现以下错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''????' at line 1

加载SQL文件的核心代码很简单:

try (Stream<String> stream = Files.lines(Paths.get(IMPORT_SQL_FILE)))
{
stream.forEach(line ->
{
try
{
// Yes it could be batched but I omitted it for simplicity
executeStatement(connection, line);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
});
}

如果我直接在 MySQL 中加载该文件,我会收到以下错误消息:

1 row(s) affected, 1 warning(s): 1300 Invalid utf8 character string: 'F18E91'

因此我的问题是如何从 Java 中生成带有二进制数据的 SQL 文件?

最佳答案

将您的 BLOB 数据内联到十六进制文字中:

StringBuilder sb = new StringBuilder(a.length * 2);
for(byte b: data) {
sb.append(String.format("%02x", b));
}
String sql = "INSERT INTO myTable (column1, column2, column3) "
+ "VALUES (1, 'hello world', x'" + sb.toString() + "');";

关于java - 如何在 Java 代码创建的 SQL 脚本文件中将 Java byte[] 转换为 MySQL BLOB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48239525/

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