我是一名新程序员,我被赋予创建一个Subject.java类的任务,在该类中,它将询问学生他们正在学习多少门科目,然后将科目信息存储到数据库中,但是问题是我当前的代码是数据库中只有一行被更新。我的代码如下,请帮助我。
System.out.print("\nEnter number of subject: ");
int sub = in.nextInt();
int i=0;
for (i=0; i<sub; i++)
{
System.out.print("\nCode: ");
this.setCode(in.next());
System.out.print("\nName: ");
this.setName(in.next());
System.out.print("\nCredit: ");
this.setCredit(in.nextInt());
// insert into database
ResultSet rs = null;
String sqlInsert = "INSERT INTO subject (code, name, credit) VALUES (?,?,?)";
try (Connection conn = MySQLDB.getConnection();
PreparedStatement pstmt
= conn.prepareStatement(sqlInsert);)
{
// assign parameters for statement
pstmt.setString(1, this.getCode());
pstmt.setString(2, this.getName());
pstmt.setInt (3, this.getCredit());
pstmt.addBatch();
if (pstmt.executeUpdate() == 1)
{
System.out.println("\nNew subject has been created succesfully!");
}
else
{
System.out.println("\nError");
}
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
}
正如Nexevis
所说,您需要将Connection
代码放在for-loop
之外,如下所示:
// insert into database
ResultSet rs = null;
String sqlInsert = "INSERT INTO subject (code, name, credit) VALUES (?,?,?)";
System.out.print("\nEnter number of subject: ");
int sub = in.nextInt();
int i = 0;
try {
Connection conn = MySQLDB.getConnection();
PreparedStatement pstmt
= conn.prepareStatement(sqlInsert);
for (i = 0; i < sub; i++) {
System.out.print("\nCode: ");
this.setCode( in.next());
System.out.print("\nName: ");
this.setName( in.next());
System.out.print("\nCredit: ");
this.setCredit( in.nextInt());
// assign parameters for statement
pstmt.setString(1, this.getCode());
pstmt.setString(2, this.getName());
pstmt.setInt(3, this.getCredit());
pstmt.addBatch();
}
try {
// execute it to insert the data
pstmt.executeBatch();
} catch (SQLException e) {
System.out.println("Error message: " + e.getMessage());
return; // Exit if there was an error
}
conn.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}