phpmyadmin 通过Java在MySQL中插入文件文件路径

slwdgvem  于 2022-11-09  发布在  PHP
关注(0)|答案(1)|浏览(111)

我的java程序从文本字段中收集文件路径:

pathField.getText();

并将结果插入到我的数据库(phpMyAdmin)中。但是,它似乎不包括反斜杠()。
数据库中的FilePath字段被设置为“Text”。我已经在System.out语句中测试了pathField.getText(),它打印时带有反斜杠。

Statement st = (Statement) conn.createStatement();

            String query_to_update = "INSERT INTO `evidence_db`.`mcases` ("
                    + "`PID`,"
                    + " `FilePath`) "
                    + "VALUES ("
                    + "DEFAULT,"
                    + " '" + pathField.getText() + "');";

            System.out.println("Query: " + query_to_update);

            int val = st.executeUpdate(query_to_update);

请注意,我已经编辑了上面的代码,所以可能会有一些小错误。

yxyvkwin

yxyvkwin1#

您应该使用预处理语句来避免此类错误

public static void main(String args[]) {

  Connection con = null;
  PreparedStatement pst = null;
  ResultSet rs = null;

  try {

  Class.forName(driver);
  con = DriverManager.getConnection(connection);

  String sql =
  "select * from Employees where FirstName " + "in(?,?,?)";
  pst = con.prepareStatement(sql);

  pst.setString(1, "komal");
  pst.setString(2, "ajay");
  pst.setString(3, "santosh");

  rs = pst.executeQuery();
  System.out.println("EmployeeID\tFirstName");
  while (rs.next()) {
  System.out.print("  "+rs.getString(1));
  System.out.print("\t\t"+rs.getString(2));
  System.out.println("\t\t"+rs.getString(3));
  }

  } catch (Exception e) {
  System.out.println(e);
  }
  }
}

所以在你的情况下

String query_to_update = "INSERT INTO `evidence_db`.`mcases` ("
                    + "`PID`,"
                    + " `FilePath`) "
                    + "VALUES (?,?);";

PreparedStatement pst=coneection.prepareStatement(query_to_update);
pst.setString(1,"DEFAULT");
pst.setString(2,pathField.getText());
pst.executeUpdate();

相关问题