Reputation: 210
I want to insert a data using JDBC, whenever I execute the program then it shows me some Mysql error:
Insert statement:
String sql = "INSERT into books(name, isbn, author, category, desc, published) VALUES('"+name+"','"+isbn+"','"+author+"','"+category+"', '"+desc+"','"+book_published+"')";
I am trying to convert the string to date here using :
String yr = year.getSelectedItem().toString();
String mn = month.getSelectedItem().toString();
String dy = day.getSelectedItem().toString();
String book_date = yr+"-"+mn+"-"+dy;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd",
Locale.ENGLISH);
try{
Date book_published = df.parse(book_date);
}catch(...){...}
and it shows me error like :
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc, published) VALUES('skd flakj','klsdjf askj','kl jasdklfj kl','kls djfklj f' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
Please help me figure out what is the problem here.
Upvotes: 0
Views: 100
Reputation: 2710
desc
is not a particularly good column name because it's a reserved word in MySQL. I'm not sure if this is the only issue here but you may want to try surrounding desc
with ticks, like so:
String sql = "INSERT into books(`name`, `isbn`, `author`, `category`, `desc`, `published`) VALUES('"+name+"','"+isbn+"','"+author+"','"+category+"', '"+desc+"','"+book_published+"')";
It's good practice anyway.
Edit: and as others have mentioned, prepared statements are safer when saving untrusted input to a database.
Upvotes: 0
Reputation: 403
desc is a reserved word for MySQL, which means u can just use it plainly.
To use it without getting an error from MySQL, u should use ` surround the reserved word.
Ps: u SQL statement may suffer from SQL injection if using user-inputed parameters, attackers can use it to get control of ur system.Maybe u should try to hv a look on this one.
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
Upvotes: 1