0

患者の配列をループする拡張 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());
    }
}
4

2 に答える 2

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 バッチ挿入:

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

ところで、SQL インジェクションを回避するには、Statement ではなくPreparedStatementを使用します

于 2013-04-19T10:12:47.950 に答える
1

ステートメントint res = stmt.executeUpdate(patientInsertSQL);は for ループ内にある必要があります。

于 2013-04-19T10:13:44.507 に答える