jdbc - 210323 - 01
封装JDBC
DBUtil
package bgy;
import java.sql.*;
public class DBUtil {
private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/test?&useSSL=false&serverTimezone=UTC";
private static final String USER = "root";
private static final String PASSWORD = "admin";
private DBUtil(){}
static {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL,USER,PASSWORD);
}
public static void close(Connection conn, Statement stmt, ResultSet rs){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
测试DBUtil
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Demo01 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
String sql = "select * from t_user where loginpwd=?";
ps = conn.prepareStatement(sql);
ps.setString(1,"111");
rs = ps.executeQuery();
while (rs.next()){
String loginName = rs.getString("loginname");
System.out.println(loginName);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(conn,ps,rs);
}
}
}
悲观锁 / 行级锁
悲观锁 / 行级锁
在select后面添加 for update
加上的话在结束运行期间,,,这个参数不能修改