1.将图片存入数据库
try
{
File f=new File(photopath);//photopath为图片的路径
FileInputStream fis=new FileInputStream(f);
sqlcommand="insert into Directory values('"+name+"','"+na+"','"+tp+"','";
sqlcommand+= mp+"',"+groupid+",?,'"+rm+"')";
ps=mycon.con.prepareStatement(sqlcommand);
ps.setBinaryStream(1,fis,(int)f.length());
ps.executeUpdate();
JOptionPane.showMessageDialog(null,"联系人["+name+"]添加成功!","提示",JOptionPane.PLAIN_MESSAGE);
flag=true;
}
catch(FileNotFoundException fnfe)
{
JOptionPane.showMessageDialog(null,fnfe.getMessage(),"异常",JOptionPane.ERROR_MESSAGE);
}
catch(IOException ioe)
{
JOptionPane.showMessageDialog(null,ioe.getMessage(),"异常",JOptionPane.ERROR_MESSAGE);
}
2.从数据库中读出图片
try
{
MyCon mycon=new MyCon();
Statement stmt=mycon.con.createStatement();
String querycommand="SELECT * FROM Directory, User_Group WHERE ";
querycommand+="Directory.GroupId=User_Group.Group_ID And Name='"+name+"'";
ResultSet rs=stmt.executeQuery(querycommand);
while(rs.next())
{
byte b[] = new byte[10*1024];
int c=0;
try
{
File f = new File("Icon//demo.jpg");//先指定一临时图片,存放从数据库中读出的图片
FileOutputStream fos = new FileOutputStream(f);
InputStream is = rs.getBinaryStream("Photo");
while ((c=is.read(b))!=-1)
{
fos.write(b, 0, c);
}
fos.flush();
fos.close();
is.close();
}//try
catch(FileNotFoundException enfe) { }
catch(IOException ioe) { }
jbphoto.setIcon(new ImageIcon(b));//将读出的图片设置为按钮的图标
}//while
stmt.close();
mycon.con.close();
}//try
catch(SQLException sqle) { }