Nauman Ahmad Nauman Ahmad - 2 years ago 118
MySQL Question

The follwoing query give me MySQLSyntaxErrorException what is wrong with Qurey

The following exception is thrown when ever i execute the following qury

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