2

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.

Iban Arriola
  • 2,526
  • 9
  • 41
  • 88
  • possible duplicate of [Syntax error due to using a reserved word as a table or column name in MySQL](http://stackoverflow.com/questions/23446377/syntax-error-due-to-using-a-reserved-word-as-a-table-or-column-name-in-mysql) – Ian Ringrose May 06 '14 at 10:14

2 Answers2

4

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

String sql = "INSERT INTO MESSAGE("
               + "`From`,"
               + "`To`,"
               + "Message,"
               + "Date,"
               + "`Read`) "
               + "VALUES(?,?,?,?,?)";
juergen d
  • 201,996
  • 37
  • 293
  • 362
3

Change From,Read and Date to any other column name which is not a SQL keyword. Find list of Reserved Words in MySQL

Abubakkar
  • 15,488
  • 8
  • 55
  • 83