此实现为用java访问mysql的blob,对图片进行存取
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
import java.io.*;
-
import java.util.*;
-
import java.sql.*;
-
-
public class BlobPros
-
{
-
private static final String URL = "jdbc:mysql://10.144.123.63:3306/mtools?user=wind&password=123&useUnicode=true";
-
private Connection conn = null;
-
private PreparedStatement pstmt = null;
-
private ResultSet rs = null;
-
private File file = null;
-
-
public BlobPros()
-
{
-
}
-
-
-
-
-
-
-
public void blobInsert(String infile) throws Exception
-
{
-
FileInputStream fis = null;
-
try
-
{
-
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
-
conn = DriverManager.getConnection(URL);
-
-
file = new File(infile);
-
fis = new FileInputStream(file);
-
-
pstmt = conn.prepareStatement("insert into tmp(descs,pic) values(?,?)");
-
pstmt.setString(1,file.getName());
-
-
pstmt.setBinaryStream(2,fis,fis.available());
-
pstmt.executeUpdate();
-
}
-
catch(Exception ex)
-
{
-
System.out.println("[blobInsert error : ]" + ex.toString());
-
}
-
finally
-
{
-
-
pstmt.close();
-
fis.close();
-
conn.close();
-
}
-
}
-
-
-
-
-
-
-
-
-
public void blobRead(String outfile,int picID) throws Exception
-
{
-
FileOutputStream fos = null;
-
InputStream is = null;
-
byte[] Buffer = new byte[4096];
-
-
try
-
{
-
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
-
conn = DriverManager.getConnection(URL);
-
pstmt = conn.prepareStatement("select pic from tmp where id=?");
-
pstmt.setInt(1,picID);
-
rs = pstmt.executeQuery();
-
rs.next();
-
-
file = new File(outfile);
-
if(!file.exists())
-
{
-
file.createNewFile();
-
}
-
fos = new FileOutputStream(file);
-
is = rs.getBinaryStream("pic");
-
int size = 0;
-
-
-
-
-
-
-
-
while((size = is.read(Buffer)) != -1)
-
{
-
-
fos.write(Buffer,0,size);
-
}
-
-
}
-
catch(Exception e)
-
{
-
System.out.println("[OutPutFile error : ]" + e.getMessage());
-
}
-
finally
-
{
-
-
fos.close();
-
rs.close();
-
pstmt.close();
-
conn.close();
-
}
-
}
-
-
public static void main(String[] args)
-
{
-
try
-
{
-
-
BlobPros blob = new BlobPros();
-
-
blob.blobRead("c:/downloads/1.jpg",47);
-
}
-
catch(Exception e)
-
{
-
System.out.println("[Main func error: ]" + e.getMessage());
-
}
-
}
-
}
参考资料:http://www.cublog.cn/u/2550/?u=http://www.cublog.cn/u/2550/showart.php?id=9900
(责任编辑:IT) |