public class LoginPreparedStatement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String user = sc.nextLine();
System.out.println("请输入密码:");
String password = sc.nextLine();
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
try {
conn = JDBCUtil.getConnection();
conn.setAutoCommit(false);
String sql = "SELECT * FROM USER WHERE username = ? AND passwor = ? ";
psmt = conn.prepareStatement(sql);
psmt.setString(1,user);
psmt.setString(2,password);
rs = psmt.executeQuery();
if(rs.next()){
System.out.println("注册成功");
}else {
System.out.println("注册失败");
}
/*----------conn.commit()---------------*/;
} catch (SQLException e) {
try { if(conn != null){
conn.rollback();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
JDBCUtil.close(rs,psmt,conn);
}
}
}
第一次写上面的代码,漏掉了事务的提交,导致在往数据库表中添加注册名失败,不过表中ID因为定义了自增1,就算没有提交事务,也会自增1.有点没明白原理,有没有同学解释一下哟。 |
|