存储图片:
//加载驱动程序类
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:denglu","sa","sa");
//建立数据库联机,其中denglu为数据库名,sa为连接数据库的帐号及密码。
Statement stmt=con.createStatement(); //建立Statement对象
FileInputStream str=new FileInputStream(filename); //图片文件路径
String sql="insert into picturenews(id,image) values(?,?,?)";
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1,id); //ID号
pstmt.setBinaryStream(2,str,str.available()); //图片数据
pstmt.execute();
//将数据存入数据库
out.println("Success,You Have Insert an Image Successfully");
图片读取:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:denglu","sa","sa");
Statement stmt=con.createStatement();
ResultSet rs=null;
String sql = "select image from picturenews WHERE id="+id;
rs=stmt.executeQuery(sql);
if(rs.next()) {
//图片输出的输出流
InputStream in = rs.getBinaryStream("image");
byte b[] = new byte[0x7a120];
for(int i = in.read(b); i != -1;)
{
//将缓冲区的输入输出到页面
in.read(b);
}
}
/**
* 获得数据后可以按照自己的方法进行处理或者显示
*/
JLabel label=new JLabel(new ImageIcon(b)); //用JLabel进行显示
.....