Nauman Ahmad Nauman Ahmad - 1 year ago 81
MySQL Question

The following query causes a MySQLSyntaxErrorException - what is wrong with my query?

The following exception is thrown when ever I execute the following query

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '-name, cpy-address, cpy-contact) VALUES('nauman','ahmad18',12)' at line 1

Query which is causing exception

String query="insert into company(cpy-name, cpy-address, cpy-contact)VALUES(?,?,?)";
Connection con=DataAccessLayer.getConnection();

PreparedStatement stat=con.prepareStatement(query);
stat.setString(1, cname);
stat.setString(2, caddress);
stat.setInt(3,x );
int rowsAffected = stat.executeUpdate();

Answer Source

You cannot use - in SQL queries. Escape the column names using ` back quote or back tick characters.

insert into company(`cpy-name`, `cpy-address`, `cpy-contact`)VALUES(?,?,?)

On another note, if the database is in your control, change to column names to use '_' rather '-'. Having illegal characters and quoting them is not a good practice. Hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download