java如何将图片存入mysql数据库



存入图片

import java.sql.*;
import java.io.*;
public class InsertImg
{
public static void main(String args[])
{
try {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
Connection con=DriverManager.getConnection( "jdbc:odbc:DBImg" );
String sql = "insert into DBImg (image) values (?)" ;
PreparedStatement pstmt=con.prepareStatement(sql);
FileInputStream fi= new FileInputStream( "./room.jpg" );
pstmt.setBinaryStream( 1 ,fi,fi.available());
pstmt.execute();
fi.close();
pstmt.close();
con.close();
} catch (Exception e){System.out.println(e.getMessage());}
}
}
把图片取出输出到文件
import java.io.*;
import java.sql.*;
 
public class ImgRead
{
public static void main(String args[])
{
try
{
Class.forName( "com.microsoft.jdbc.sqlserver.SQLServerDriver" );
String url= "jdbc:microsoft:sqlserver://BILLGATES:1433" ;
Connection cn=DriverManager.getConnection(url, "sa" , "8310" );
Statement st=cn.createStatement();
String str = "select img from test where id=1" ;
ResultSet rs=st.executeQuery(str);
rs.next();
InputStream in=rs.getBinaryStream( 1 );
 
FileOutputStream file = new FileOutputStream( "./88.mp3" );
byte c[] = new byte [ 1024 ];
 
int r = 0 ;
 
while ((r = in.read(c)) != - 1 ){
file.write(c, 0 ,r);
 
}
 
 
 
file.close();
in.close();
 
 
 
 
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
把图片输出到JLabel控件
import java.awt.*;
import java.applet.*;
import java.awt.image.BufferedImage;
import com.sun.image.codec.jpeg.*;
import javax.swing.*;
import java.sql.*;
import java.io.*;
public class DisplayImg
{
public DisplayImg(){
Image img= null ;
try {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
Connection con=DriverManager.getConnection( "jdbc:odbc:DBImg" );
Statement stmt=con.createStatement();
String sql = "select image from DBImg" ;
ResultSet rs=stmt.executeQuery(sql);
rs.next();
InputStream in = rs.getBinaryStream( 1 );
JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
img=decoder.decodeAsBufferedImage();
rs.close();
con.close();
} catch (Exception e){System.out.println(e.getMessage());}
 
JFrame f= new JFrame();
JLabel label= new JLabel();
ImageIcon icon= new ImageIcon(img);
label.setIcon(icon);
JScrollPane jsp= new JScrollPane(label);
Container content=f.getContentPane();
content.add(jsp);
f.setSize( 535 , 400 );
f.setVisible( true );
 
}
 
public static void main(String args[]){
DisplayImg di= new DisplayImg();
}
}
 

上面的程序数据库驱动不一致,自行修改一下.其中在Sqlserver中要存放图片的字段应选"image"类型

源代码来源:http://www.cnblogs.com/qixin622/archive/2010/09/01/1814658.html


你可能感兴趣的:(java,mysql)