import java.awt.Image;
import java.io.*;
import java.sql.*;import javax.swing.*;
public class DBtest extends JFrame{
static Connection conn = null;
static Statement stat=null;
Image images=null;
JButton button=new JButton("按钮");

//static ImageIconimage = new ImageIcon("1.jpg");
static JLabel label = new JLabel();
JScrollPane jspy=new JScrollPane(label);
public static ResultSet db(String sql){
ResultSet rs;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/logindb?user=root&password=123456"); 
stat=conn.createStatement();
rs = stat.executeQuery(sql);
return rs;
}catch(Exception e){
e.printStackTrace();
}
return null;
}

public DBtest(){
//设置窗体的关闭动作、标题、大小位置以及可见性


ResultSet rs=null;
String sql = "select photoname,photo from phototable where id=1";
rs = db(sql);
byte[] bb=null;
String filename=null;
try {
if(rs.next()){
//filename=rs.getString(1);
bb = rs.getBytes(2);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
label.setIcon(new ImageIcon(bb));
//label.setText(filename);
this.add(label);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("数据库图片查看器");
this.setBounds(100,100,980,440);
this.setVisible(true);
}
public static void main(String args[]){
new DBtest();
}}

解决方案 »

  1.   


    public OtherTest() {
    ResultSet rs = null;
    String sql = "select imgurl from t_user where id=1";
    rs = db(sql);
    String filename = null;
    try {
    if (rs.next()) {
     filename=rs.getString(1);
    }
    } catch (SQLException e) {
    e.printStackTrace();
    }
    label.setIcon(new ImageIcon(filename));
    this.add(label);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle("数据库图片查看器");
    this.setBounds(100, 100, 980, 440);
    this.setVisible(true);
    }
    还有就是路径格式为:D:\\abc.gif
      

  2.   

    我是把照片存进数据库之中,存放类型为blob,通过byte流读出来,而不是把照片的路径存进数据库中。
      

  3.   

    噢  这样啊,刚试了下bb = rs.getBytes(1);
    label.setIcon(new ImageIcon(b));存的时候:
    File f = new File("D:/abc.gif");
    FileInputStream fis = new FileInputStream(f);
    PreparedStatement ps = conn.prepareStatement(sql);
    ps.setBinaryStream(1, fis, (int) f.length());