
how to upload a text file into a database using jchooser

import java.io.*;
import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
public class UploadTextFile {
static File file;
public static void main(String[] args) throws Exception {
JLabel label=new JLabel("Choose File: ");
final JTextField text=new JTextField(20);
JButton b1=new JButton("Browse");
JButton b2=new JButton("Upload");
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JFileChooser chooser=new JFileChooser();
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
text.setText(file.getPath());
}
}
});
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
FileInputStream fis = new FileInputStream(file);
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
PreparedStatement pstmt = conn.prepareStatement("insert into myfile( file_name, file_data) values ( ?, ?)");
pstmt.setString(1, file.getName());
pstmt.setBinaryStream(2, fis, (int) file.length());
pstmt.executeUpdate();
JOptionPane.showMessageDialog(null,"Uploaded successfully to database");
pstmt.close();
conn.close();
}
catch(Exception ex){
System.out.println(ex);
}
}
});
JFrame f=new JFrame();
f.setLayout(null);
label.setBounds(10,10,100,20);
text.setBounds(110,10,100,20);
b1.setBounds(220,10,80,20);
b2.setBounds(310,10,80,20);
f.add(label);
f.add(text);
f.add(b1);
f.add(b2);
f.setVisible(true);
f.setSize(450,200);
}
}