How to insert Image in MySQL Database with Java in NetBeansIDE
How to insert Image in MySQL Database with Java in NetBeansIDE.
1. Open NetBeansIDE
2. Make a new Java Application project.
3. Make a JFrame Form and Design it as in this project.
4. Right Click on 'Choose File' button and Goto events~action~actionPerformed
5. Make a table in your MySQL DB say 'Image' with one Image column of LongBlob type.
6. Enter the code in it(in actionPerformed for Choose File Button).
(Fix all imports)
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:mysql://localhost/new", "root", "root");
PreparedStatement ps=con.prepareStatement("insert into `Image` 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);
}
6. Run the JFrame Form.
7. Choose the file to insert in DB.
8. Check the File in DB.
9. Finish.
Thank You :)
Image Insertion in Database:
Facebook Page
Comments
Post a Comment