出于任务的目的,我必须将图像存储在mysql中作为blob格式(即使将图像路径存储在数据库中并保留该图像路径并保持在Localcopy中的文件夹中的图像)。
到目前为止,我已经研究了,找不到任何可以帮助我的答案,这就是我到目前为止所做的
立即单击按钮,这将被触发:
empdao.insertImage(fis);
图像填充在另一个类似的听众中:
static FileInputStream fis = null;
static String path = null;
path = filechooser.getSelectedFile().getAbsolutePath();
File image = new File(path);
fis = new FileInputStream (image);
下面的此代码将其添加到数据库中。
public void insertImage(FileInputStream fis) throws SQLException {
Connection c = getConnection();
String query = "INSERT INTO Picture (picture) VALUES (?)";
System.out.println(query);
PreparedStatement pstmt = c.prepareStatement(query);
pstmt.setBinaryStream(1, fis);
pstmt.executeUpdate();
c.close();
}
但是问题是我需要它作为斑点转换为斑点,我不确定如何帮助我或指导我如何将所选图像作为斑点字段存储到mysql中。p>当前将其添加到数据库中时,我在"图片"列下获取Java.io文件输入。
假设您在MySQL中有一个表id INT PRIMARY KEY
, CC_2, name VARCHAR(255),
和 photo BLOB
。
然后,您可以使用以下Java代码将新图片插入BLOB
:
public class InsertPictureAsBlob {
public static void main(String[] args) throws Exception, IOException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager
.getConnection("jdbc:mysql://localhost/databaseName", "username", "password");
String INSERT_PICTURE = "INSERT INTO my_picures(id, name, photo) VALUES (?, ?, ?)";
conn.setAutoCommit(false);
File file = new File("myPhoto.png");
try (FileInputStream fis = new FileInputStream(file);
PreparedStatement ps = conn.prepareStatement(INSERT_PICTURE)) {
ps.setString(1, "001");
ps.setString(2, "name");
ps.setBinaryStream(3, fis, (int) file.length());
ps.executeUpdate();
conn.commit();
}
}
}
1)首先,您将要确保在MySQL模式中创建了一个具有斑点列类型(blob,edimedblob,longblob)中创建的表。查看MySQL中可用的BLOB列类型,然后选择适当的尺寸。
2)您将要从使用语句切换到准备态度。
String query = "INSERT INTO Pictures (Picture) VALUES (?)";
PreparedStatement pstmt = conn.prepareStatement(query);
3)您当前正在将FileInputStream传递给方法,因此您只需要在准备安排上使用SetBinaryStream方法。
pstmt.setBinaryStream(1, fis);
4)然后在准备安排上执行executeUpdate()。
pstmt.executeUpdate();
使用原始代码中的异常处理,并进行适当清理对象(数据库连接,准备的语句),类似于您在原始代码中的内容。