重写代码遇到的bug:
示例代码如下:
package cn.kgc.Dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDao {
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
private boolean getConnection() {
boolean flag = false;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/kgcnews?user=root&password=41312019";
connection = DriverManager.getConnection(url);
flag = true;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
private void closeConnection() {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet executeQuery(String sql, Object[] params) {
if (this.getConnection()) {
try {
pstmt = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pstmt.setObject(i+1, params[i]);
}
rs = pstmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
}
this.closeConnection();
return rs;
}
public int executeUpdate(String sql, Object[] params) {
int lines = 0;
if (this.getConnection()) {
try {
pstmt = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pstmt.setObject(i+1, params[i]);
}
lines = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
this.closeConnection();
return lines;
}
public static void main(String[] args) {
BaseDao test = new BaseDao();
String sql = "select id, title from news_detail where id=?";
Object[] params = {2};
ResultSet rs = test.executeQuery(sql, params);
try {
System.out.println(rs.next());
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
while (rs.next()) {
int id = rs.getInt("id");
System.out.println(id);
String title = rs.getString("title");
System.out.println(title);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
bug1:java.sql.SQLException: Operation not allowed after ResultSet closed
,出现这个bug的原因是在executeQuery方法中我先关闭了资源在进行返回,但是一旦关闭了资源之后ResultSet里面的资源就丢失了,所以不应该关闭资源再返回。
bug2:结果界面只显示了个true,但是并不输出内容,这是因为在我的结果集rs里面只有一个元素,而在上面输入rs.next()去判断里面是否有值得时候使得指针移动了以为,所以下面的while就拿不出来值了。
bug3:将上述两bug解决完了之后,把main函数改为如下,但是还是报bug1,猜想原因可能是ResultSet返回值的地址一直没变,所以如果在拿值之前就关闭的话就会出错。只需把关闭资源的方法放到最后面即可。
public static void main(String[] args) {
BaseDao test = new BaseDao();
String sql = "select id, title from news_detail where id=?";
Object[] params = {2};
ResultSet rs = test.executeQuery(sql, params);
test.closeConnection();
try {
while (rs.next()) {
int id = rs.getInt("id");
System.out.println(id);
String title = rs.getString("title");
System.out.println(title);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
网友评论