我有一个增强的 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/