2

I've got this error from my jdbc driver. I don't know why, tho.

Here's the corresponding code:

try {
    String colNames = " ";
    for (int i=0; i<cols.size(); i++) {
        if (i == cols.size()-1) {
            colNames += cols.get(i);
        } else if (i<cols.size()) {
            colNames += cols.get(i)+", ";
        }               
    }       
    String colValues = " ";
    for (int i=0; i<values.size(); i++) {
        if (i == values.size()-1) {
            colValues += values.get(i);
        } else if (i<values.size()) {
            colValues += values.get(i) + ", ";
        }       
    }
    System.out.println(
        "INSERT INTO `" + tableName + "` (" + colNames + ") VALUES (" + colValues + ") "
    );
    //System.out.println(kerdojel);

    PreparedStatement pst = connHandler.conn.prepareStatement
        ("INSERT INTO `" + tableName + "` (" + colNames + ") VALUES (" + colValues + ") ");
    pst.executeUpdate();
    pst.close();
}

"values" and "cols" are ArrayLists that contains the data from the JTable. cols are the Column names and values are the cell values.

The output for the Sysout:

INSERT INTO `TableOne` ( nev, kor, lakhely) VALUES ( asd, 1, asd) 

The error:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'asd' in 'field list'
3
  • use single inverted commas for values. On a side note use setString() etc methods to set the values Commented Mar 26, 2016 at 18:06
  • Thanks, but still, I got the error. Commented Mar 26, 2016 at 18:12
  • show the output of query and the error Commented Mar 26, 2016 at 18:16

2 Answers 2

2

That is not how the PreaparedStatement was intended to be used. When you use a PreparedStatement, you can specify the values by using one of the "set" methods.

Here is an example:

String colNames = " ";
String colValues = " ";
for (int i=0; i<cols.size(); i++) {
    if(i!=0){
       colNames += ", ";
       colValues += ", ";
    }
    colNames += cols.get(i);
    colValues += "?";              
}       

try (PreparedStatement pst = connHandler.conn.prepareStatement("INSERT INTO `" + tableName + "` (" + colNames + ") VALUES (" + colValues + ") ");){

    for (int i = 0; i < values.size(); i++) {
        pst.setString(i+1,values.get(i));       
    }

    pst.executeUpdate();
}

You should use the appropriate "set" method based on the column's data type (setInt(...), setDate(...), etc.). You can find more details here

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

Comments

0

Try to use command like these one to check problem existed.

PREPARE mycmd FROM 'INSERT INTO TableOne(nev,kor) VALUES (?, ?)'

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.