public void addUser() {
Connection c=DBCPUtil.getConnection();
try {
PreparedStatement ps=c.prepareStatement("insert into user(username,password) values(?,?)");
ps.setString(1, "auto");
ps.setString(2, "123");
ps.executeUpdate();
} catch (SQLException e) {
System.out.println("插入数据失败!");
}
DBCPUtil.closeConnection();
}
public boolean userLoad() throws SQLException {
Scanner in =new Scanner(System.in);
System.out.println("请输入用户名:");
String name=in.next();
System.out.println("请输入密码:");
String password=in.next();
Connection c=DBCPUtil.getConnection();
try {
PreparedStatement ps=c.prepareStatement("select * from user where username=? and password=?");
ps.setString(1, name);
ps.setString(2, password);
ResultSet rs=ps.executeQuery();
if(rs.next()){
System.out.println("登录成功!");
return true;
}else{
System.out.println("用户名或密码不正确!");
}
} catch (SQLException e) {
System.out.println("数据加载失败!");
}
DBCPUtil.closeConnection();
return false;
}
addUser();
userLoad();
(DBCPUtil是我包装的一个类里面有获取连接的方法)
调用这两个方法,为什么第一个方法最后关闭连接之后,第二方法无法重新连接到数据库?
应该先关闭rs.close(),在关闭ps.close(),在关闭c..close()
你是用的单元测试还是main 方法启动,不是在web 环境下吧,单看代码,感觉没错,楼上说的其实只要关闭 c 就可以,如果是一个方法,可以不关闭,节省时间。
估计 Connection 写成共享变量了!