尝试在Netbeans的Patient表中添加多个患者

时间:2013-04-19 10:11:06

标签: 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());
    }
}

2 个答案:

答案 0 :(得分:3)

您必须在每次迭代时执行查询或使用 SQL Batch Insert

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而不是使用Statement

答案 1 :(得分:1)

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