从Java向MySQL插入/更新blob
在谷歌搜索了一天之后,我终于决定是时候去问问那些无所不能的SO社区了。我正在尝试将图像插入或更新到从Java向MySQL插入/更新blob,java,mysql,sql,blob,mysql-workbench,Java,Mysql,Sql,Blob,Mysql Workbench,在谷歌搜索了一天之后,我终于决定是时候去问问那些无所不能的SO社区了。我正在尝试将图像插入或更新到MySQL数据库中。我使用的查询和代码如下: FileInputStream inputStream = new FileInputStream(file); String[] str_array = file.getName().split("-"); String stringb = str_array[1]; String stringc = str_arra
MySQL
数据库中。我使用的查询和代码如下:
FileInputStream inputStream = new FileInputStream(file);
String[] str_array = file.getName().split("-");
String stringb = str_array[1];
String stringc = str_array[2];
String fingerName = stringc.substring(0, 2);
//gets file name and splits it accordingly
String id = getID.id(stringb); //does a sql lookup to get the previously inserted id according to the stringb(users unique id number)
String INSERT_PIC = "INSERT INTO database.user_picture(id_ref, picture_num, user_image) values('" + id + "', ?, ?) ON DUPLICATE KEY UPDATE user_image = ?;";
//creates the sql statement that inserts or updates according to the primary keys id_ref and picture_num
ps = (PreparedStatement) connection.prepareStatement(INSERT_PIC);
ps.setString(1, fingerName);
ps.setBinaryStream(2, (InputStream) inputStream, file.length());
ps.setBinaryStream(3, (InputStream) inputStream, file.length());
//creates the prepared statement and inserts the 3 parameters
ps.executeUpdate();
connection.commit();
//executes the query on the connected database
我很肯定这会奏效。测试时,它将正确地将图像插入数据库。更新时,除blob/image字段改为NULL外,所有字段均正确更新
我不知道为什么会发生这种情况,也不知道是否有其他方法可以让它发挥作用,如果有任何建议,我将不胜感激。我想,在流()消耗流时,第一个挫折是什么。因此,对setBinaryStream()的第二个调用只读取“null”。您为参数2和3提供了相同的输入流。 执行语句时,首先读取参数2流,直到结束。 当JDBC驱动程序尝试读取参数3的流时,它已经在其末尾,因为它是同一个流实例 尝试提供两个输入流:
FileInputStream inputStream1 = new FileInputStream(file);
FileInputStream inputStream2 = new FileInputStream(file);
[...]
ps.setBinaryStream(2, (InputStream) inputStream1, file.length());
ps.setBinaryStream(3, (InputStream) inputStream2, file.length());
另外,不要忘了关闭一些最终块中的流
祝你好运。两个不同的输入流同时读取同一个文件会导致异常吗?从逻辑上讲,我认为这可能会导致类似于线程死锁的情况。只要它们都只是在读,就不会引起任何问题。