我们可以使用java从MySql数据库中获取添加的图像吗?

时间:2010-01-30 07:40:51

标签: java mysql blob

我已将图像添加到MySql数据库中。我试图通过使用java创建一个新文件从数据库中获取图像。问题是一切都很好,图像文件已经创建,但图像文件不包含图像,它没有任何东西,新创建的图像文件的大小不同于原来的..... Sql代码:

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');

和java代码:

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

4 个答案:

答案 0 :(得分:1)

您从流中读取,但从未将读取的字符保存到缓冲区中......

while (is2.read() > 0) 
{
    fos.write(buffer);
    fos.flush();
}

类似的东西:

int x;

while((x = is2.read()) != -1)
{
   fos.write(x);
}

fos.flush();

(编辑 - 从另一个答案的评论......)

对于不插入图像的插入语句,请参阅this link

/*

Defining the Table: Oracle and MySql

create table MyPictures (
   id INT PRIMARY KEY,
   name VARCHAR(0),
   photo BLOB
);
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class InsertPictureToMySql {
  public static void main(String[] args) throws Exception, IOException, SQLException {
    Class.forName("org.gjt.mm.mysql.Driver");
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/databaseName", "root", "root");
    String INSERT_PICTURE = "insert into MyPictures(id, name, photo) values (?, ?, ?)";

    FileInputStream fis = null;
    PreparedStatement ps = null;
    try {
      conn.setAutoCommit(false);
      File file = new File("myPhoto.png");
      fis = new FileInputStream(file);
      ps = conn.prepareStatement(INSERT_PICTURE);
      ps.setString(1, "001");
      ps.setString(2, "name");
      ps.setBinaryStream(3, fis, (int) file.length());
      ps.executeUpdate();
      conn.commit();
    } finally {
      ps.close();
      fis.close();
    }
  }
}

答案 1 :(得分:0)

insert into pictures values('1','pic1','D:\java.jpg');

不将二进制jpg数据插入数据库,它会插入字符串D:\java.jpg

答案 2 :(得分:0)

您在写入输出流时遇到问题,应该是这样的:

while ((buffer[0] = is2.read()) > 0) 
            {
                fos.write(buffer[0]);
                fos.flush();
            }

你的图片应该作为BLOB保存在数据库中!

P.S。你的缓冲区是无用的,因为它的大小为1,你应该至少使它512或1024来逐字节读取。

希望它有所帮助。

答案 3 :(得分:0)

// create a file called MySqlInsertBlob.java
//==========import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Blob;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.*;

class MySqlInsertBlob {
FileOutputStream image;
Connection conn = null;
PreparedStatement pstmt = null;
Statement stmt= null;
ResultSet res = null;
StringBuffer query=null;
String filename ="c:/backblue.gif";

public MySqlInsertBlob(){

try{

query=new StringBuffer("insert into blobs(filename,binarydata,name) values (?,?,?)");
File file= new File(filename);

Class.forName("com.mysql.jdbc.Driver")…
conn = DriverManager.getConnection("jdbc:mysql:…
stmt=conn.createStatement();
pstmt=conn.prepareStatement(query.toSt…
pstmt.setString(1, filename);
pstmt.setBinaryStream(2, new FileInputStream(filename),(int)file.leng…
pstmt.setString(3,"silviya");
pstmt.executeUpdate();
System.out.println("Successfully inserted into BLOBS .....");

ResultSet rs=stmt.executeQuery("select * from blobs where name='silviya'");
if (rs.next()) {
Blob test=rs.getBlob("binarydata");
InputStream x=test.getBinaryStream();
int size=x.available();
OutputStream out=new FileOutputStream("c:/xyz.gif");
byte b[]= new byte[size];
x.read(b);
out.write(b);


}
}catch(ClassNotFoundException cnfe){

System.out.println("ClassNotFoundExcep… occured :"+cnfe);
}catch(SQLException se){

System.out.println("SQLException occured :"+se);
}catch(FileNotFoundException fe){

System.out.println("File Not Found Exception occured :"+fe);
}catch(Exception e){

System.out.println("Exception occured :"+e);
}finally{
try{
stmt.close();
conn.close();
}catch(Exception e){}
}
Source(s):