【问题标题】:My SQL insert statement, string variable has apostrophe [duplicate]Mysql插入语句,字符串变量有撇号[重复]
【发布时间】:2021-03-09 18:37:06
【问题描述】:

我正在尝试使用 java 中的 INSERT 语句将数据插入 MySQL 数据库。但是,我使用的变量之一包含一个撇号,我不确定如何在语句中说明它。

public static void addAlbum(Album album) throws Exception {    
        
        try{
            Connection conn = getDBConnection();
            PreparedStatement posted = conn.prepareStatement(
                    "INSERT INTO album(title, year, singer, company) VALUES ('" + album.getName() +"', '"+ album.getYear() +"', '"+ album.getSinger() +"', '"+ album.getCompany() +"')"
            );
            posted.executeUpdate();
        }
        catch(Exception e) {
            System.out.println(e);
        }
        finally{System.out.println("Insert completed");}
    }

album.getName() 检索到“我回来了”的字符串,我该怎么做才能正确插入该值,而不是用撇号切断字符串并使语句无效?

【问题讨论】:

    标签: java mysql


    【解决方案1】:

    假设所有的值都是String类型,你应该这样做:

    String sql = "INSERT INTO album(title, year, singer, company) VALUES (?, ?, ?, ?)";
    PreparedStatement posted = conn.prepareStatement(sql);
    posted.setString(1, album.getName());
    posted.setString(2, album.getYear());
    posted.setString(3, album.getSinger());
    posted.setString(4, album.getCompany());
    

    这还将保护您的数据库免受SQL injection 的侵害。

    注意:如果year是一个整数,你应该做posted.setInt(2, album.getYear());

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-07
      • 2011-05-12
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-22
      相关资源
      最近更新 更多