我从用户通过 Scanner
输入的另一个方法传递我的方法 InsertQuery
变量。
如何将 iName
、iType
等填写到我的 iQuery
中,以便我可以将它们插入到我的数据库中?
public void InsertQuery (String iName, String iType, int health_Problem, Date date2, String aRemind, String docName, String docType, String docAdress)
{
final String url = "jdbc:mysql://localhost/ehealthdb?serverTimezone=UTC";
final String DBUSER = "root";
final String DBPSWD = "root";
try {
Connection con = DriverManager.getConnection(url,DBUSER,DBPSWD);
Statement stmt = con.createStatement();
String iQuery = "INSERT into appointment"
+ "(ID, PatientID, Insurance_Name, Insurance_Type, Health_Problem, Appointment_Date, Appointment_Remind, Doctor_Name,Doctor_Type,Doctor_Adress)"
+ "values ('1','1',,'Gesetzlich','5','15.01.2020','1 Week','Musterarzt','Hausarzt','Musterstraße')";
stmt.executeUpdate(iQuery);
} catch (Exception e) {
System.out.println("Something went wrong @InsertQuery");
}
}
最佳答案
最简单的方法可能是使用PreparedStatement
:
public void insertQuery
(String iName, String iType, int healthProblem, Date date2, String aRemind, String docName, String docType, String docAddress)
throws SQLException {
final String url = "jdbc:mysql://localhost/ehealthdb?serverTimezone=UTC";
final String DBUSER = "root";
final String DBPSWD = "root";
try (Connection con = DriverManager.getConnection(url,DBUSER,DBPSWD);
PreparedStatement stmt = con.prepareStatement(
"INSERT into appointment" +
"(ID, PatientID, Insurance_Name, Insurance_Type, Health_Problem, Appointment_Date, Appointment_Remind, Doctor_Name, Doctor_Type, Doctor_Adress) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")) {
stmt.setString(1, iName);
stmt.setString(2, iType);
stmt.setInt(3, healthProblem);
stmt.setTimestamp(4, new Timestamp(date2.getTime()));
stmt.setString(5, aRemind);
stmt.setString(6, docName);
stmt.setString(7, docType);
stmt.setString(8, docAddress);
stmt.executeUpdate();
}
}
https://stackoverflow.com/questions/65534066/