代码之家  ›  专栏  ›  技术社区  ›  Sasikumar Murugesan

带有特殊字符(“\N”、“\S”和“\T”)的JDBC查询插入

  •  1
  • Sasikumar Murugesan  · 技术社区  · 7 年前

    我有原始的插入查询,比如

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

    得到 SqlException

    由于名称字段中有特殊字符(“\N”),jdbc insert查询失败。

    那么如何克服并插入带有\N的名称呢?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Gord Thompson    7 年前

    最干净的方法是根本不使用原始SQL查询。如您所述,如果您从其他进程接收到名称,那么它可能在 String 参数化查询 要执行插入:

    // 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();
    
    推荐文章