Iban Arriola Iban Arriola - 3 months ago 18
MySQL Question

insert into giving problems

I made a simple insert into statement but it is not working well. The error that it gives to me is


com.mysql.jdbc.exceptions.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 'From, To, Message,
Date, Read) VALUES (3,1,'iepa','2012-10-16 16:26:42',0)' at line 1


this is the code of my sql.

Connection conn = Connect.getConnection();
try{
Statement stmt = conn.createStatement();
String sql = "INSERT INTO MESSAGE("
+ "From,"
+ "To,"
+ "Message,"
+ "Date,"
+ "Read) "
+ "VALUES(?,?,?,?,?)";
PreparedStatement pstat = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstat.setInt(1, user.getId());
pstat.setInt(2, Integer.parseInt(who.getText().toString()));
pstat.setString(3, message.toString());
pstat.setTimestamp(4, new Timestamp(new Date().getTime()));
pstat.setInt(5, 0);
pstat.executeUpdate();


As you see I am not doing nothing strange or so difficult but I cannot run it.

Answer

You need to escape reserved words in MySQL like from with backticks

String sql = "INSERT INTO MESSAGE("
               + "`From`,"
               + "`To`,"
               + "Message,"
               + "Date,"
               + "`Read`) "
               + "VALUES(?,?,?,?,?)";
Comments