I have added an image into a MySql database. And I am trying to fetch the image from the database by creating a new file by using java. The problem is that everything goes fine and image file has been created but the image file doesn't contain the image, it has just nothing and the size of the new created image file differs from the original one..... The Sql Code:
CREATE TABLE `pictures` ( `id` int(11) NOT NULL auto_increment, `description` varchar(20) default NULL, `photo` blob, PRIMARY KEY (`id`) );
insert into pictures values('1','pic1','D:\java.jpg');
And the java code:
public class ReadBlobPicture
{
static String url = "jdbc:mysql://localhost:3306/imgdatabase";
static String username = "root";
static String password = "tiger";
public static void main(String[] args)
throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, username, password);
String sql = "SELECT photo FROM pictures where id=1";
Statement stmt = conn.prepareStatement(sql);
ResultSet resultSet = stmt.executeQuery(sql);
Object obj = resultSet;
while (resultSet.next())
{
File image = new File("E:\\java12.jpg");
FileOutputStream fos = new FileOutputStream(image);
System.out.println(resultSet.getString(1));
byte[] buffer = new byte[1];
InputStream is2 = resultSet.getBinaryStream(1);
System.out.println(is2.available());
while (is2.read() > 0)
{
fos.write(buffer);
fos.flush();
}
fos.close();
}
conn.close();
}
}