JDBC编程六步曲:
1.注册驱动
2.获取数据库链接
3.获取数据库操作对象
4.执行SQL语句
5.处理查询结果集
6.关闭资源
package com.yj;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class jdbc{
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取数据库连接
String url = "jdbc:mysql://localhost:3306/yj?serverTimezone=UTC";
String user = "root";
String password = "123456";//这里是密码
conn = DriverManager.getConnection(url,user,password);
//3.获取数据库操作对象
stmt = conn.createStatement();
//4.执行SQL语句:DML语句
String sql = "select * from user";
rs = stmt.executeQuery(sql);
//5.处理查询结果集
while(rs.next()){
String ename = rs.getString("name");
String sex = rs.getString("sex");
System.out.println("姓名:" +ename);
System.out.println("性别:"+sex);
}
}catch (Exception e){
e.printStackTrace();
}finally{
//6.关闭资源
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
进阶事务与行级锁
package com.jdbc02;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCTest12 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/bjpowernode";
String user = "root";
String password = "******";
conn = DriverManager.getConnection(url, user, password);
//关闭事务的自动提交,开始事务
conn.setAutoCommit(false);
String sql = "select * from bank where job = ? for update"; //for update 行级锁
ps.setString(1, "manager");
rs = ps.executeQuery();
while (rs.next()) {
rs.getString("job");
}
conn.commit();
} catch (Exception e) {
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}finally {
//关闭资源
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}