为什么INSERT INTO包含blob不能保留记录

时间:2018-11-27 22:57:27

标签: java mysql

我正在使用Java和Serenity编写自动化测试,并且需要数据库包含文件。我没有成功。

测试将在Windows,Mac和Linux上的localhost上运行,因此绝对文件名将不起作用。我无法使INSERT INTO LOAD_FILE正常工作;我不知道它的当前文件夹在哪里。

我尝试了直接编码到数据库。为了方便起见,这些文件来自项目文件夹。 (这与使用Spring / Hibernate HQL的程序访问不同)。我没有收到错误,但记录没有显示在我的测试页或MySQL Workbench中。

MySQL代码:

CREATE TABLE IF NOT EXISTS other_resources (
    id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
    orgid INTEGER NOT NULL,
    res_name VARCHAR(255),
    res_blob LONGBLOB NOT NULL,
    CONSTRAINT fk_other_resources_orgid FOREIGN KEY (orgid) REFERENCES orgs (id) ON DELETE CASCADE
);

我尝试了三种不同的代码组合。所有成功。我不确定是否必须复制文件,或者是否使用Statement方法。

int orgId = rsOrg.getInt(1);
Path path = FileSystems.getDefault().getPath(".");

File file = new File(path.toString(), "pom.xml");
finStream = new FileInputStream(file);
byte[] fecho = new byte[(int) file.length()];
prepstatem = connection.prepareStatement("INSERT INTO other_resources (orgid, res_name, res_blob) VALUES(?, ?, ?)");
prepstatem.setInt(1, orgId);
prepstatem.setNString(2, "AnotherRes");
prepstatem.setBinaryStream(3, finStream, file.length());
int b = prepstatem.executeUpdate();
finStream.read(fecho);
finStream.close();

File fileT = new File(path.toString(), "serenity.properties");
FileInputStream finST = new FileInputStream(fileT);
PreparedStatement pst = connection.prepareStatement("INSERT INTO other_resources (orgid, res_name, res_blob) VALUES(?, ?, ?)");
pst.setInt(1, orgId);
pst.setNString(2, "SerpropRes");
pst.setBlob(3, finST);
int c = pst.executeUpdate();
System.out.println("INSERT INTO tom " + c);
finST.close();

File fileD = new File(path.toString(), "database.properties");
FileInputStream finsDB = new FileInputStream(fileD);
byte[] dbecho = new byte[(int) fileD.length()];
Blob blobDB = new SerialBlob(dbecho);
PreparedStatement prest = connection.prepareStatement("INSERT INTO other_resources (orgid, res_name, res_blob) VALUES(?, ?, ?)");
prest.setInt(1, orgId);
prest.setNString(2, "DatabaseRes");
prest.setBlob(3, blobDB);
int d = prest.executeUpdate();
System.out.println("INSERT INTO tom " + d);
finsDB.close();

我查询数据库以查看是否已添加记录。报告了所有三个文件的id,res_name和res_blob大小。但是,我正在运行的应用程序未显示记录,而MySQL Workbench未显示记录。

Statement stOR = connection.createStatement();
String queryOR = "SELECT * FROM other_resources";
ResultSet rsOR = stOR.executeQuery(queryOR);
while (rsOR.next())
{
    System.out.println("id " + rsOR.getInt(1));
    System.out.println("orgid " + rsOR.getInt(2));
    System.out.println("name " + rsOR.getString(3));
    System.out.println("blob length " + rsOR.getBlob(4).length());
}

当我在MySQL Workbench中使用脚本添加记录时,它显示的ID为4,就像我希望添加这3个文件一样。

关于MySQL,我有什么想念的吗?

1 个答案:

答案 0 :(得分:1)

我添加connection.commit();

后就可以使用它