java - 尝试将多个患者添加到 Netbeans 中的患者表中

标签 java database netbeans

我有一个增强的 for 循环,可以循环遍历我的患者数组。

在这个循环中,我有一个插入语句,用于插入患者的号码、姓名、地址和电话号码。

但是,当数组中有多个患者时,数据库中先前的患者就会被覆盖。有什么方法可以让我到达表格的下一行,这样我就不会覆盖以前的所有条目?

这是我正在使用的方法。

public void databaseSave( ArrayList <Patient> pList )
    {

    try
    {
        String name = "Shaun";
        String pass = "Shaun";
        String host = "jdbc:derby://localhost:1527/DentistDatabase";

        Connection con = DriverManager.getConnection(host, name, pass);

        Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

        //Statement stmt = con.createStatement();

        System.out.println("Before the delete");


        String query = "DELETE "
                    +  "FROM SHAUN.PATIENT";


        System.out.println("After the delete");


        stmt.executeUpdate(query);


        String select = "SELECT * FROM SHAUN.PATIENT";

        ResultSet result = stmt.executeQuery(select);


        System.out.println("Before loop");

        for ( Patient p: pList )
        {

            patientInsertSQL = "Insert Into SHAUN.PATIENT VALUES (" + p.getPatientNum() + ", '"
            + p.getPatientName() + "', '" + p.getPatientAddress() + "', '"
            + p.getPatientPhone() + "')";


            System.out.println("In the loop!");

        }


        int res = stmt.executeUpdate(patientInsertSQL);

        System.out.println(res);


        stmt.close();
        result.close();
        con.commit();

        System.out.println("After Loop and close");

    }
    catch (SQLException err)
    {
        System.out.print(err.getMessage());
    }
}

最佳答案

您必须在每次迭代时执行查询或使用SQL 批量插入

for ( Patient p: pList )
        {
            patientInsertSQL = "Insert Into SHAUN.PATIENT VALUES (" + p.getPatientNum() + ", '"+ p.getPatientName() + "', '" + p.getPatientAddress() + "', '"
            + p.getPatientPhone() + "')";
        int res = stmt.executeUpdate(patientInsertSQL);

}

SQL Batch Insert :

for(Patient p:pList) {
PatientInsertSQL = "Insert into patient Values(x,y,z)";
stmnt.addBatch(query);
}
stmnt.executeBatch();

顺便说一句,要避免 SQL Injection使用PreparedStatement而不是声明

关于java - 尝试将多个患者添加到 Netbeans 中的患者表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16102240/

相关文章:

javascript - 创建另一个帐户后显示失败 "Sorry, your registration failed. Please go back and try again."

java - 在 netbeans 中创建/访问库

java - 如何在 Netbeans 中构建 Web 应用程序后运行 .war 文件

java - 如何更改确认对话框中的是/否选项?

java - JavaCC 与 ANTLR 的优势是什么

java - ews-java-api - 无法设置类的实例

java - Spring 不能正常工作但没有错误信息

mongodb - 我怎样才能处理一个非常大的数据库而不错过性能?

ios - 如何使用 Firestore 数据库快速设置 TableView 中项目列表的后缀?

java - 无法从 NetBeans 提交到 Subversion