Add data to a Database(Java)


  1. Open the last NetBeans project
  2. Add new jFrame Form(I name it as table)
  3. Design it as following
  4. I added 3 Text Fields and 3 Labels
  5. Change label's names as ID, Name, Adress
  6. Change text field's variable name as follow
    • txtID
    • txtName
    • txtAdress
  7. Import the following libraries
  8.         import java.sql.Connection;
            import java.sql.PreparedStatement;
            import java.sql.ResultSet;
            import javax.swing.JOptionPane;
    
            
  9. Defind the following variables in the 'table' class
    (My jFrame name is table)
  10.     Connection conn=null;
        ResultSet rs=null;
        PreparedStatement pst=null;
        
        
  11. After the defin variable there is a method named "table()"
  12. Add the following code there
  13. conn=dbcon.Connect
  14. Here,
    • dbcon is we made datasabe connection class name
      If you don't know about it please follow this link
  1. Double click on the "Add" button and add the codes below
  2.         try{
               String sql="insert into empdata(ID,Name,Adress)values(?,?,?)";
               pst=conn.prepareStatement(sql);
               pst.setString(1, txtID.getText());
               pst.setString(2, txtName.getText());
               pst.setString(3, txtAdress.getText());
               pst.execute();
               JOptionPane.showMessageDialog(null, "saved");
           }   
           catch(Exception e){JOptionPane.showMessageDialog(null, e);}
           
  3. Now run your project
  4. In the running time if you got error like this,
    • go to 'service'
    • Right click on Java DB
    • Click 'Start Server'
  5. Now run the project again

Impotent things

  • Add your own data fields
    This programm consits only the basic
  • To add this data to a database you must have this data fields in your database
    If you don't know to make a database, please follow this link

No comments:

Post a Comment