java中基于用户输入的数据库更新
我是一名新程序员,我被分配了一个任务来创建一个类Subject.java,在这个类中,它会询问学生他们正在学习多少科目,然后将科目信息存储到数据库中,但我当前代码的问题是数据库中只更新了一行。我的代码如下,请帮助我java中基于用户输入的数据库更新,java,database,jdbc,Java,Database,Jdbc,我是一名新程序员,我被分配了一个任务来创建一个类Subject.java,在这个类中,它会询问学生他们正在学习多少科目,然后将科目信息存储到数据库中,但我当前代码的问题是数据库中只更新了一行。我的代码如下,请帮助我 System.out.print("\nEnter number of subject: "); int sub = in.nextInt(); int i=0;
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());
}
System.out.print(“\n输入主题编号:”);
int sub=in.nextInt();
int i=0;
对于(i=0;i正如Nexevis
所说的,您需要将连接
代码置于for循环
之外,如下所示:
// 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
}
pstmt.close();
conn.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
//插入数据库
结果集rs=null;
String sqlInsert=“插入主题(代码、名称、信用)值(?,?)”;
System.out.print(“\n输入主题编号:”);
int sub=in.nextInt();
int i=0;
试一试{
连接conn=MySQLDB.getConnection();
编制报表
=conn.prepareStatement(sqlInsert);
对于(i=0;i
至少,对于每一行,您可能不应该关闭连接,您应该在循环之前打开它并重用它来插入每一行,然后一起执行更新。我不明白,您可以尝试(Connection conn=MySQLDB.getConnection()
用于每一行。这将连接到数据库并每次关闭它,因此要更新100行,您将连接到数据库100次并关闭它100次。要么是这样,要么是您将}
放错了位置,并且它不像此处显示的那样位于for
循环中。发布完整的方法。为了帮助您在编程和调试过程中,我建议您重构代码,以遵循每个方法都应负责单个任务的原则。因此,在您的案例中,我建议使用一个方法来运行并收集用户输入。一旦收集到这些输入(例如,在ArrayList中),然后运行这些输入并将它们添加到批处理中以进行插入。这将帮助您更轻松地缩小调试会话期间中断的内容。虽然连接
应该在for
循环之外,但您仍然应该像OP一样使用try with
资源。这是确保连接正确关闭,易于阅读。