Reputation: 2744
I have java code which connect to MySQL and retrive data. I have following code and it always give SQLSyntaxErrorException
and says there is syntax error in line 1. I cant understand why. Please help me. I can sure the names are correct.
private void saveDetails(int slct) throws SQLException {
if(slct == ADD_NEW_RECORD) {
String query = "INSERT INTO emp(?,?,?,?,?,?,?,?,?,?,?,?,?,?) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement st = Main.db.con.prepareStatement(query);
st.setString(1, "epfno");
st.setString(2, "fname");
st.setString(3, "lname");
st.setString(4, "sex");
st.setString(5, "nid");
st.setString(6, "address");
st.setString(7, "birthday");
st.setString(8, "position");
st.setString(9, "tpno");
st.setString(10, "fathername");
st.setString(11, "mothername");
st.setString(12, "m_status");
st.setString(13, "comments");
st.setString(14, "photo_id");
st.setInt(15, emp.epfno);
st.setString(16, emp.fname);
st.setString(17, emp.lname);
st.setInt(18, emp.sex);
st.setString(19, String.copyValueOf(emp.nid));
st.setString(20, emp.address);
st.setDate(21, emp.birthday);
st.setString(22, emp.position);
st.setString(23, emp.tpno);
st.setString(24, emp.fathername);
st.setString(25, emp.mothername);
st.setBoolean(26, emp.m_status);
st.setString(27, emp.comments);
st.setString(28, emp.photo_id);
st.execute();
}
}
Upvotes: 0
Views: 268
Reputation: 18474
You can't pass in column names as ? parameters. You would need to name the columns in your query and only pass the values in as parameters
Upvotes: 3
Reputation: 500177
You cannot specify column names as parameters. Try spelling them out in your query:
INSERT INTO emp(epfno, fname, lname,...
and getting rid of the first half of the st.setXXX
calls.
Upvotes: 3
Reputation: 4645
You cannot parameterize the name of the columns, so your SQL needs to look something like this:
INSERT INTO emp(epfno, fname, ...) VALUES (?, ?, ...)
Upvotes: 3
Reputation: 1499840
You're trying to set the field names as parameters - you can't do that. You can only specify values as parameters. So basically your first 14 setString
calls should go away, and you should put those field names in the SQL:
String query = "INSERT INTO emp(epfno, fname, lname, sex, nid, address, "
+ "birthday, position, tpno, fathername, mothername, m_status, "
+ "comments, photo_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
st.setInt(1, emp.epfno);
st.setString(2, emp.fname);
st.setString(3, emp.lname);
// etc
Upvotes: 7