JDBC 将变量插入数据库

JDBC inserting variables to database

我正在从用户通过 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,除了许多其他好处外,它还解决了以下两个重要问题:

  1. 它可以帮助您保护您的应用程序免受 SQL Injection
  2. 您不必自己将文本值括在单引号内。

典型用法如下图:

String query = "INSERT INTO appointment(ID, PatientID, Insurance_Name, Insurance_Type, Health_Problem) VALUES (?, ?, ?, ?, ?)";

try (PreparedStatement pstmt = con.prepareStatement(query)) {
    //...
    
    pstmt.setString(1, id);
    pstmt.setString(2, patientId);
    pstmt.setString(3, insuranceName);
    //...

    pstmt.executeUpdate();
} catch(SQLException e) {
    e.printStackTrace();
}

请注意,对于每个 ?,您都必须使用 pstmt.setXXX。您需要了解的另一件事是,在方法调用中,pstmt.setString(1, Id)1 指的是第一个 ? 而不是 table.[=23= 中的第一列]

其他一些要点:

  1. 我使用了 try-with-resources 语句,这是一种在程序完成后关闭资源的更简单且推荐的方法。从 Oracle's tutorial 了解更多信息。
  2. 始终关注 Java naming conventions 例如Insurance_Name 应命名为 insuranceName.

最简单的方法可能是使用 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();
    }
}

不要使用语句,使用 PreparedStatement。否则,you get hacked.

更一般地说,JDBC 是一只狡猾的野兽而不是特别好的 API。出于相当充分的理由——它被设计成最小公分母,它更侧重于暴露所有现有数据库的所有花里胡哨的东西,而不是给你,想要与数据库交互的程序员,一个很好的体验.

尝试JDBC or JOOQ

你的异常处理也是错误的。如果你捕获到一个异常,要么处理它,要么确保你抛出一些东西。记录它,(或者更糟,打印它)绝对不算数。将 throws 添加到您的方法签名中。如果那不可能(通常是可能的,请先尝试),throw new RuntimeException("Uncaught", e) 就是您想要的。不是 e.printStackTrace(),或者更糟的是,你所做的:你只是扔掉了 所有 相关信息。不要那样做。

我用过这种方法,效果很好

  • iName
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',,'"+iName+"','5','15.01.2020','1 Week','Musterarzt','Hausarzt','Musterstraße')";
        
        stmt.executeUpdate(iQuery);
        
    } catch (Exception e) {
        System.out.println("Something went wrong @InsertQuery");
    }
}