【问题标题】:MySQL: Inverted comma -> ( ' ) and double quotation -> ( " ) errors in insertion query [duplicate]MySQL:插入查询中的反逗号 -> ( ' ) 和双引号 -> ( " ) 错误 [重复]
【发布时间】:2016-03-08 09:39:51
【问题描述】:

我正在尝试使用将内存存储到 MySQL 数据库中的 NetBeans-8.0.2 和 JavaFX (FXMLApplication) 创建一个待办事项列表。

我知道,SQL 查询需要逗号 -> ( ' ) 和 双引号 -> ( " ) 一样理解一个字符串。

现在,我正在尝试的是,(今天是我姐姐的生日)我正在尝试在我的列表中添加一个任务:今天是 Rahi 的生日!

但是,由于sql查询,失败了。

这是因为在代码内部,输入的反逗号使整个 sql 查询变得复杂。

 @FXML
private void handleAddTaskAction(ActionEvent event) {
    String date = addTaskDatePicker.getValue().toString();
    System.out.println(date);
    String hour = hourComboBox.getValue() + "";
    String minute = minuteComboBox.getValue() + "";

    String where = whereField.getText();

    String header = headerField.getText();
    String description = descriptionArea.getText();

    if(hour.length()==0)
        hour= "12 AM";
    if(minute.length()==0)
        minute= "00";
    if(header.length()==0)
        header= "(No header available)";
    if(description.length()==0)
        description= "(No description available)";
    if(header.length()==0 && description.length()==0){
        header= "(Empty task)";
        description= "(Empty description)";
    }

    String query = "insert into task values('" + date + "','" + hour + " " + minute + " minutes', '"
            + header + "', '" + description + "', 'at " + where + "');";

    if (date.length() >= 1) {
        try {
            statement.execute(query);
        } catch (SQLException ex) {
            //Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);

            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText("Error occured!");
            alert.showAndWait();
        }
    } else {
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setHeaderText("You must select a date.");
        alert.showAndWait();
    }

}

我想在输入时存储消息。有什么解决办法吗?

我的数据库表描述和图形用户界面如图所示。 问我是否还需要什么。 谢谢。

图片:GUI 和 图片来自:Table description

【问题讨论】:

  • 使用转义字符,参见:stackoverflow.com/questions/881194/…
  • SQL 查询将逗号-> ( ' ) 和双引号-> ( " ) 当作理解字符串一样。 不,单引号和双引号有不同含义。单引号用于数据字符串,双引号用于模式中的名称。

标签: java mysql javafx fxml netbeans-8


【解决方案1】:

只需使用PreparedStatement 注入您的值,它会为您转义它们。

【讨论】:

  • 是的。 PreparedStatement 将处理您从未预料到的各种引用/转义问题。从用户输入手动粘贴 SQL 查询只是在乞求 SQL 注入攻击。但是一个代码示例会很好地完善这个答案。
猜你喜欢
  • 2018-08-18
  • 1970-01-01
  • 2023-04-03
  • 2021-01-16
  • 2018-07-16
  • 1970-01-01
  • 2012-05-17
  • 2016-05-13
  • 1970-01-01
相关资源
最近更新 更多