public static void main(String[] args){
Connection con = null;
PreparedStatement ps = null;
try {
// 从键盘录入账号密码:
Scanner sc = new Scanner(System.in);
System.out.println("账号");
String name = sc.nextLine();
System.out.println("密码");
String pwd = sc.nextLine();
// JDBC步骤:
// 1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("加载驱动成功");
// 2.获取连接
con = DriverManager.getConnection("jdbc:mysql:///studet?useUnicode=true&characterEncoding=utf8","root","root");
System.out.println("获取连接成功");
// 3.创建会话 -- 预编译
ps = con.prepareStatement("SELECT * FROM T_USER WHERE username =? AND PASSWORD=?");
System.out.println("创建会话成功");
// 4.设置?的值,并且执行:
ps.setString(1,name);
ps.setString(2,pwd);
ResultSet rs = ps.executeQuery();// ResultSet 结果集
System.out.println("发送sql成功");
if (rs.next()) { // 有且只有一条用if 多条用while
System.out.println("欢迎您" + name + ",登陆成功!");
}else{
System.out.println("对不起,您登陆的账号或密码错误,登陆失败!");
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally{
// 6.关闭数据库资源
try {
if (ps != null){
ps.close();// 避免空指针异常
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (con != null){
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
银行转账案例讲解事务问题
public static void main(String[] args){
Connection con = null;
Statement sta = null;
try {
// JDBC步骤:
// 1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("加载驱动成功");
// 2.获取连接
con = DriverManager.getConnection("jdbc:mysql:///studet?useUnicode=true&characterEncoding=utf8","root","root");
System.out.println("获取连接成功");
// 3.创建会话
sta = con.createStatement();
// 4.发送sql,执行
// 将事务的自动提交取消/关闭
con.setAutoCommit(false);
sta.executeUpdate("update t_account set balance = balance - 500 where id = 1");
sta.executeUpdate("update t_account set balance = balance + 500 where id = 2");
// 手动提交事务,将上面的逻辑全部控制在一个事务当中
con.commit();
System.out.println("发送sql成功");
// 4.处理结果
System.out.println("处理成功");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally{
// 6.关闭数据库资源
try {
if (sta != null){
sta.close();// 避免空指针异常
}
} catch (SQLException e) {
try {
// 回滚事务
con.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
e.printStackTrace();
}
try {
if (con != null){
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}