gpt4 book ai didi

java - 哪个地方写connection.close()和preparedstatement.close()

转载 作者:行者123 更新时间:2023-12-02 05:22:51 30 4
gpt4 key购买 nike

我是 JDBC 新手...

Student类有Constructor、add()、update()和delete()等方法...

在构造函数中打开连接。下面代码中的 conn.close() 和 pstmt.close() 写在哪个位置帮助我

class Student
{
Connection conn;

PreparedStatement pstmt;

ResultSet rs;

public Student()
{
try
{
Class.forName("com.mysql.jdbc.Driver");

conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
}
catch(Exception e)
{
System.out.println("Error :"+e.getMessage());
}

}


public void add(int rollno,String name)
{
try
{
pstmt = conn.prepareStatement("insert into student values (?, ?)");

pstmt.setInt(1,rollno);

pstmt.setString(2, name);

int i = pstmt.executeUpdate();

if (i != 0) {
System.out.println("Record Inserted");
} else {
System.out.println("Record Not Inserted");
}

}
catch(Exception e)
{
System.out.println("Error :"+e.getMessage());
}

}

public void update(int rollno,String name)
{
try
{
pstmt = conn.prepareStatement("update student set name=? where rollno=?");

pstmt.setString(1, name);

pstmt.setInt(2,rollno);


int i = pstmt.executeUpdate();

if (i != 0) {
System.out.println("Record Updated");
} else {
System.out.println("Record Not Updated");
}


}
catch(Exception e)
{
System.out.println("Error :"+e.getMessage());
}
}

public void delete(int rollno)
{
try
{
pstmt = conn.prepareStatement("delete from student where rollno=?");

pstmt.setInt(1,rollno);


int i = pstmt.executeUpdate();

if (i != 0) {
System.out.println("Record Deleted");
} else {
System.out.println("Record Not Deleted");
}

}
catch(Exception e)
{
System.out.println("Error :"+e.getMessage());
}
}

}

最佳答案

我想您应该添加另一个方法来关闭连接,并在完成操作后在对象上调用它。

public void closeConnection() {
conn.close();
}

另外,最好创建另一个方法来打开连接,而不是从构造函数中打开它。

关于java - 哪个地方写connection.close()和preparedstatement.close(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26356079/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com