1

I am new to programming and i am trying to make an small Java swing application using netbeans IDE and i have designed the Form and created an table too i used the following code to insert data into database from the form but i am getting many errors please help me to correct this code:

import java.sql.*;
public class db
{
  static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
  static final String DB_URL = "jdbc:mysql://localhost:3306/userdb";
  static final String USER="root";
  static final String PASS="toor";

  Connection conn = null;
  Statement stmt = null;
  static final String d_unit=jTextField2.getText();
  static final String d_name=jTextField3.getText();
  static final String d_dob=jDateChooser2.getText();
  //static final String d_gender="gender";
  static final String d_age=jTextField4.getText();
  static final String d_doorno=jTextField5.getText();
  static final String d_street=jTextField6.getText();
  static final String d_vc=jTextField7.getText();
  static final String d_district=jTextField8.getText();
  static final String d_pin=jTextField9.getText();
  static final String d_phone=jTextField10.getText();
  static final String d_mail=jTextField11.getText();
  static final String d_occupations=jTextField12.getText();
  try
  {
     Class.forName("com.mysql.jdbc.Driver");
     conn=DriverManager.getConnection(DB_URL,USER,PASS);
     stmt = conn.createStatement();
     stmt.executeUpdate("insert into donors (unit,name,dob,age,doorno,street,vc,district,pin,phone,mail,occupation) values('"+d_unit+"','"+d_name+"','"+d_dob+"','"+d_age+"','"+d_doorno+"','"+d_street+"','"+d_vc+"','"+d_district+"','"+d_pin+"','"+d_phone+"','"+d_mail+"','"+d_occupations+"')");
     JOptionPane.showMessageDialog(null,"Inserted Successfully!");
     }
    catch(Exception e)
    {     }

   }
4
  • @Gerret I think the problem here is compile time errors. Commented Aug 28, 2013 at 12:59
  • You're inserting all values as VARCHAR. Are these actually defined as varchars in database? For example doorno or age look like integers. I would also strongly recommend use PreparedStatement instead Statement. See Using PreparedStatement Commented Aug 28, 2013 at 13:10
  • @Axel well that questions explain that not very good! And the header is actully not the topic... but ok ^^ Commented Aug 28, 2013 at 13:17
  • what is stacktrace?? @ Gerret Commented Aug 28, 2013 at 15:25

4 Answers 4

3

You may not use the final String because, then you can't modify these Strings, and the other code is correct, but i think you can use the ? in the line:

String sql="INSERT INTO ´donors´ (unit,name) VALUES (?,?)";
    //put the rest of the sentence
      try {
        PreparedStatement pdt = cn.prepareStatement(sql);
        pdt.setString(1, jTextField2.getText();
        pdt.setString(2, jTextField3.getText();
        //put the rest of the code
        int n1=pdt.executeUpdate();
      if(n1>0)
      {
      JOptionPane.showMessageDialog(null,"Inserted Successfully!");
      }
      }catch (SQLException ex) { }

Well, that's the largest way, but the most correct. I hope this helps.

Sign up to request clarification or add additional context in comments.

4 Comments

I TRIED YOUR method for inserting data into mysql table but still couldn't insert the data i am getting many errors here is my complete code pastie can you please help me to fix the problem ?? here is my pastie link
ok but i need the lines where you have the errors and the kind of errors exceptions
Here is the lines which are leading to error and the corresponding error static final String JDBC_DRIVER="com.mysql.jdbc.Driver";/*Illegal start of expression*/ Class.forName("com.mysql.jdbc.Driver");/*illegal start of type*/ conn=DriverManager.getConnection(DB_URL,USER,PASS);/*cannot find symbol*/ stmt = conn.createStatement();/*Unreported Sql Exception must be caught or thrown*/ PreparedStatement pdt = conn.prepareStatement(sql);/*Unreported Sql Exception must be caught or thrown*/ pdt.setString(1,jTextField2.getText());/*Identifier expected*/ still
Your problem in that code is you're declaring variables as static final inside this method: private void jButton1ActionPerformed(java.awt.event.ActionEvent evt). That's not correct. Take a look to this tutorial for a better understanding of using static modifier.
1
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {                                        
    String itemCode = txtItemCode.getText();
    String itemName = txtItemName.getText();
    String unitPrice = txtUnitPrice.getText();
    String qty = txtQty.getText();
    String query = "insert into items values ('"+itemCode+"','"+itemName+"','"+unitPrice+"','"+qty+"')";
    System.out.println(query);


    try {
        Connection c = DBClass.getConnection();
        Statement stmt = c.createStatement();
        stmt.executeUpdate(query);
        JOptionPane.showMessageDialog(this, "Saved");
    } catch (Exception e) {
        e.printStackTrace();
    }

// DBClass

import java.sql.Connection;
import java.sql.DriverManager;

/**
 *
 * @author Nadun
 */
public class DBClass {

    static private Connection  connection;

    public static Connection getConnection() throws Exception{
        if(connection == null){
            //JDBC
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/stock", "root", "123");
        }
        return connection;
    }

}

Comments

1

Everything looks alright. Maybe the trouble is on your mysql database?

Check the data type of your row in mysql, if your data type in the current row is "int", then it should be like this

try
{
 Class.forName("com.mysql.jdbc.Driver");
 conn=DriverManager.getConnection(DB_URL,USER,PASS);
 stmt = conn.createStatement();
 stmt.executeUpdate("insert into donors (name, age) values('"+d_name+"',,'"+Integer.valueOf(d_age.getText().toString())+"')");
 JOptionPane.showMessageDialog(null,"Inserted Successfully!");
 }
catch(Exception e){     }

}

You should be careful with data types. If your mysql row is int type then in your java you should give it int time as well.

I guess your data type of "name" row is text that use string, and your data type of "age" row is int?

I check your code is giving a string value from your java to your int mysql row. that's the error.

So you should convert the string to the int first

Integer.valueOf(d_age.getText().toString());

Comments

0

try proceeding like this for simplicity and less error-prone

String sql = "INSERT INTO donors(unit,name,dob,age,doorno,street,vc,district,pin,phone,mail,occupation) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
stmt.executeUpdate(sql);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.