java - JDBC 向数据库中插入变量

我从用户通过 Scanner 输入的另一个方法传递我的方法 InsertQuery 变量。

如何将 iNameiType 等填写到我的 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/

相关文章:

node.js - 如何动态地从 Firestore 数组中删除多个元素?

reactjs - firebase safari 错误消息 : This browser does

typescript - TypeScript 如何推断回调参数类型

python - numpy 中的 3d 矩阵乘法

hash - 如何从 elixir 中的 map 创建 `hash` 或 `md5`?

java - 更正应包含单个兼容版本的应用程序的类路径

c - STM32创建RAM段

python - Pandas:如何用另一个值替换 int 子字符串

r - 无法为 R 中的列表替换 NA 的拼写错误

scala - 基于Map从List[String]转换为List[Int]