【问题标题】:Trying to add more than one Patient into my Patient table in Netbeans尝试在 Netbeans 中将多个患者添加到我的患者表中
【发布时间】:2013-04-19 10:11:06
【问题描述】:

我有一个增强的 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());
    }
}

【问题讨论】:

  • 执行应该在for循环内完成。

标签: java database netbeans


【解决方案1】:

您必须在每次迭代时执行查询或使用 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 而不是语句

【讨论】:

    【解决方案2】:

    int res = stmt.executeUpdate(patientInsertSQL); 语句应该在 for 循环中。

    【讨论】:

    • 太好了,解决了。感谢您的帮助 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    相关资源
    最近更新 更多