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

时间:2012-12-14 16:49:48

标签: java mysql phpmyadmin

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

pathField.getText();

并将结果插入我的数据库(phpMyAdmin)。但是,它似乎不包括反斜杠()。 EG - C:UsersSteveDesktop

数据库中的FilePath字段设置为“Text”。 我在pathField.getText()语句中测试了System.out,并使用反斜杠进行打印。

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);

请注意,我已编辑了上述代码,因此可能会出现轻微错误。

1 个答案:

答案 0 :(得分:3)

你应该使用预备语句来避免这种错误

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();