2016-12-28 93 views
3

为了执行任务,我必须将图像作为Blob格式存储到MySQL中(尽管存储图像路径会更好,更理想在数据库中并将图像保存在localcopy中的文件夹中)。如何着手将图像以Blob格式保存到Java中的Java

到目前为止,我已经研究,但没有找到任何答案,可以帮助我,这是我迄今所做

不久,单击按钮,这将被解雇:

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(); 
} 

但问题是,我需要它,将其转换为一个blob,我不知道如何,有人可以帮助我或者指导我如何去选择的图像存储为一个BLOB字段成MySQL的。

当前它将它添加到数据库中时,我在图片列中获得了java.io文件输入。

+0

http://stackoverflow.com/a/41235395/267540 – e4c5

回答

3

假设您在MySQL中有一个表my_picures,其中id INT PRIMARY KEY,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(); 
     } 
    } 
} 
+0

我已经做出了修改,但是它仍然不会将图像添加到数据库中,即使使用PreparedStatement –

+0

谢谢它,因为我忘记了添加大小位 –

+0

欢迎您。 – DimaSan

2

1)首先你会想要确保你有你的MySQL架构与创建的表定义了BLOB列类型(BLOB,MEDIUMBLOB,LONGBLOB)。查看MySQL中可用的BLOB列类型并选择适当的大小。

2)您将要从使用语句切换到PreparedStatement。

String query = "INSERT INTO Pictures (Picture) VALUES (?)"; 
PreparedStatement pstmt = conn.prepareStatement(query); 

3)你正在传递一个FileInputStream你的方法,所以你只需要使用上PreparedStatement的setBinaryStream方法。

pstmt.setBinaryStream(1, fis); 

4)然后在PreparedStatement上执行executeUpdate()。

pstmt.executeUpdate(); 

利用异常处理你在你的原始代码和你在你原来的代码是什么执行的对象适当的清理(数据库连接,准备语句),相似。

+0

无论如何,我可以使用常规语句来代替PreparedStatement,因为它的任务和我必须遵循规范? –

+0

@ jomin_george94上面的代码是你应该怎么做的,你现在的代码是什么,而且我不能放任何其他方式,不安全的垃圾,而不是用Java编写好的数据库访问代码。我不确定你的意思是“必须遵循规范”,但规范通常会描述需要完成的工作,而不是应该如何实施。 –

+0

当我按照你的建议,我得到NullPointerException并且在这一行失败: –