Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 373
  • Last Modified:

How to code 'ADD' button to create new record in Java

Hello,
I just started learning Java. I created a simple form using Java Swing on NetBeans. I added some text fileds and button like 'add', 'delete' etc. I am using MySql db. What I want to do is.. by clicking 'add' button the program should be able to create new records in customer table in MySql db.
From design tab, I clicked 'add' button and right click, select event, Actionperformed and wrote the following code.

Here is my code:
private void UpdateActionPerformed(java.awt.event.ActionEvent evt) {
         fNameValue.getText();
         lNameValue.getText();
                 
         System.out.println("Adding new record");
         Connection con = null;
         String url = "jdbc:mysql://localhost:3306/";
         String db = "testdb";
         String driver = "com.mysql.jdbc.Driver";

         try {
             Class.forName(driver);
             con = DriverManager.getConnection(url+db, "root","pw");
             PreparedStatement st=con.prepareStatement
               ("insert into customer (fNameValue,lNameValue) values(?;?)");
             st.setString(1,fNameValue);
             st.setString(2,lNameValue);
             st.executeUpdate();
             JOptionPane.showMessageDialog
               (jPanel2, "Data is succesfully added");
             con.close();
         }
         catch(Exception e) {
             JOptionPane.showMessageDialog(jPanel2,"Error in submitting");

         }

    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Customer().setVisible(true);
            }
        });
    }
I am gettiing 'my exception message ... Error in submitting'

What am I doing wrong? Would it be possible to get a sample code on to create new rercords?

Thanks so much.
0
guavamay
Asked:
guavamay
1 Solution
 
brunoguimaraesCommented:
I think the problem is in these lines:

st.setString(1,fNameValue);
st.setString(2,lNameValue);

Change them too:

st.setString(1,fNameValue.getText());
st.setString(2,lNameValue.getText());

But it helps if you post the full exception stacktrace.
0
 
guavamayAuthor Commented:
Thanks for your help.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now