【问题标题】:Escape comma in MySql Statement JAVAMySql 语句 JAVA 中的转义逗号
【发布时间】:2020-03-21 21:52:16
【问题描述】:

我已经有一段时间没有使用 MySql 了。我在我的表中插入了一些数据。我试图插入一个 逗号分隔 字符串作为我的 TRAITS 列的值 例子:

“可爱、毛茸茸、懒惰”

我也希望在这些单词中插入逗号,但是,我不断收到语法错误:列数与第 1 行的值计数不匹配

    final int ADMIN_ID = 1;
    final char comma = ',';

    try {

        this.connect_func();

        statement = (Statement) connect.createStatement();

        statement.executeUpdate("INSERT INTO ANIMALS (USER_ID , NAME , SPECIES , DOB , PRICE , TRAITS)" +
                                "VALUES" + "('"+ ADMIN_ID +"', 'Bella', 'Dog', '02/12/2019', '"+950.00+"', 'Sweet" + comma +" Hyper " + comma + " Cuddly "+ comma + " obedient')," + 
                                  "('"+ ADMIN_ID +"', 'Coco', 'Cat', '07/15/2016', '"+650.00+"', 'Lazy " + comma + " Cuddly" + comma + "Stubborn');");


        statement.close();


          return true;

    } catch(Exception e) {

        System.out.println(e);

        statement.close();

        return false;
    }

【问题讨论】:

  • 了解prepared statement以防止sql注入。它还将解决您有关逗号转义的问题
  • Nfo5o,这是一个课堂项目,甚至不会实时部署。但感谢您提供非常有用的意见。
  • 同时删除价格列周围的单引号。它是一个数值。
  • 您应该始终使用准备好的语句,这样可以更轻松地使用数据库
  • 使用准备好的语句。

标签: java mysql


【解决方案1】:

使用PreparedStatement 避免SQL 注入。按如下方式进行:

String sql = "INSERT INTO ANIMALS (USER_ID, NAME, SPECIES, DOB, PRICE, TRAITS) VALUES(?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1, ADMIN_ID);
pstmt.setString(2, "Bella");
pstmt.setString(3, "Dog");
pstmt.setDate(4, java.sql.Date.valueOf("2019-12-02")); // yyyy-mm-dd
pstmt.setDouble(5, 950.0);
pstmt.setString(6, "Cuddly, Furry, Lazy");
pstmt.executeUpdate();

【讨论】:

    【解决方案2】:

    只需删除 PRICE 十进制值周围的引号 这是您的解决方案:

        final int ADMIN_ID = 1;
        final char comma = ',';
    
        try {
    
            this.connect_func();
    
            statement = (Statement) connect.createStatement();
    
            statement.executeUpdate("INSERT INTO ANIMALS (USER_ID , NAME , SPECIES , DOB , PRICE , TRAITS)" +
                                    "VALUES" + "('"+ ADMIN_ID +"', 'Bella', 'Dog', '02/12/2019', "+950.00+", 'Sweet" + comma +" Hyper " + comma + " Cuddly "+ comma + " obedient')," + 
                                      "('"+ ADMIN_ID +"', 'Coco', 'Cat', '07/15/2016', "+650.00+", 'Lazy " + comma + " Cuddly" + comma + "Stubborn');");
    
    
            statement.close();
    
    
              return true;
    
        } catch(Exception e) {
    
            System.out.println(e);
    
            statement.close();
    
            return false;
        }
    

    【讨论】:

      猜你喜欢
      • 2018-12-01
      • 2010-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多