Search code examples
javamysqljdbcspecial-characters

JDBC query insert with special character ("\N", "\S" and "\T")


I have raw insert query like

insert into sample(id, name) values(1, 'text \\N\');

Getting SqlException while trying to insert via jdbc but the same insert query is working if I insert via mysql command prompt(console).

jdbc insert query is failing due to special characters("\N") in name field.

so how to overcome and insert the name with \N?


Solution

  • The cleanest approach is to not use a raw SQL query at all. If, as you've stated, you receive the name from some other process then it is presumably in a String variable (or property, or similar) so you can simply use a parameterized query to perform the insert:

    // example data
    int theId = 1;
    String theName = "the name you received from somewhere else";
    //
    PreparedStatement ps = conn.prepareStatement("INSERT INTO sample (id, name) VALUES (?, ?)");
    ps.setInt(1, theId);
    ps.setString(2, theName);
    ps.executeUpdate();