【发布时间】:2014-10-14 08:29:55
【问题描述】:
我是 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());
}
}
}
【问题讨论】:
标签: java jdbc database-connection prepared-statement