【问题标题】:Gives me an Error when I Insert data to my Customer table [duplicate]当我将数据插入客户表时给我一个错误[重复]
【发布时间】:2019-04-25 12:27:34
【问题描述】:

我正在开发一个 Java Web Restful 应用程序,当我插入数据时,它会出现类似这样的错误..

"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 '' at line 1"

我不知道我的 SQL 语法有什么问题

我的 SQL 查询看起来像这样......

String sql = "INSERT INTO customer(fname, lname, email, phone, country, dob, city, postal, address1, address2, password, regDate, status) "
            + "VALUES ('"+customer.getFname()+"', '"+customer.getLname()+"', '"+customer.getEmail()+"', '"+customer.getPhone()+"', '"+customer.getCountry()+"',"
                    + "'"+customer.getDob()+"', '"+customer.getCity()+"', '"+customer.getPostal()+"', '"+customer.getAddress1()+"', '"+customer.getAddress2()+"',"
                    + "'"+customer.getPassword()+"', NOW(), 'active'";

除了 'dob(date)'、'regDate(date)' 之外,所有列类型都有 '(varchar)'..

谢谢!

【问题讨论】:

标签: java mysql jdbc sql-insert


【解决方案1】:

@jacob ,您不能直接在引号内传递日期对象。相反,您需要使用 DateFormatter 将其格式化为字符串类型。一旦将日期转换为字符串类型,您就可以将该值传递给列。

一个建议:不要使用这种 '','','',... 查询。它可能面临 SQL 注入。相反,您使用参数化查询,这样您的查询就无法更改。

【讨论】:

  • date 值作为字符串传递是一个非常糟糕的建议
  • @a_horse_with_no_name,你可以点赞我的评论!我说了同样的话:-)
  • 好吧,您只是建议:“您需要将其格式化为字符串类型”和“一旦您将日期转换为字符串类型,您就可以传递它列的值“。
【解决方案2】:

是的,查询中缺少右括号

但是将转义字符放在单引号('),如果数据有单引号查询会报错

 "INSERT INTO customer(fname, lname, email, phone, country, dob, city, postal, address1, address2, password, regDate, status) "
        + "VALUES ('"+escape( customer.getFname() )+"', '"
                 +escape( customer.getLname() ) +"', '"
                 +escape( customer.getEmail() ) +"', '"
                 +escape( customer.getPhone() ) +"', '"
                 +escape( customer.getCountry() )+"',"
                     +"'"+customer.getDob() +"', '"
                     +escape( customer.getCity() ) +"', '"
                     +escape( customer.getPostal() ) +"', '"
                     +escape( customer.getAddress1() ) +"', '"
                     +escape( customer.getAddress2()) +"',"
                    + "'"+escape( customer.getPassword() )+"', NOW(), 'active' )";


public static String escape(String val) {
    return (val==null?null:val.replaceAll("'", "''"));
}

【讨论】:

  • 正确的方法是使用带参数的prepared statement,而不是尝试自己引用值。
猜你喜欢
  • 2022-11-29
  • 1970-01-01
  • 2018-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多