小编Ish*_*ani的帖子

如何在netbeans java中将图像插入mysql数据库

我对编程知之甚少。我需要将图像保存在 MySQL 数据库中。我创建了一个数据库表,并且有一列用于添加具有 longblob 数据类型的图像。我有一个按钮的代码,可以从 PC 中的文件夹中选择图像,然后将其加载到 jlable。现在我需要将此图像插入到数据库中。

这是我的代码;

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    JFileChooser fc=new JFileChooser(); 
    fc.showOpenDialog(this); 
    File f=fc.getSelectedFile(); 
    String path=f.getAbsolutePath(); 
    jLabel1.setIcon(new ImageIcon(path)); 

    try{ 
        FileInputStream fin=new FileInputStream(f); 
        int len=(int)f.length(); Class.forName("com.mysql.jdbc.Driver"); 

        Connection con=DriverManager.getConnection("jdbc:my­sql://localhost/hss", "root", "bis123"); 
        PreparedStatement ps=con.prepareStatement("Insert into profile values(?)"); 

        ps.setBinaryStream(1, fin, len); 
        int status=ps.executeUpdate(); 

        if(status > 0) { 
            jLabel2.setText("Successfully inserted in DB"); 
        }else{ 
            jLabel2.setText("Image not inserted!"); 
        } 
    }catch(Exception e){
        System.out.println(e); 
    }
}
Run Code Online (Sandbox Code Playgroud)

java mysql netbeans

4
推荐指数
1
解决办法
2万
查看次数

标签 统计

java ×1

mysql ×1

netbeans ×1