一、前言
在使用MyBatis之前,在學校的編程課里,我們最先接觸的就是JDBC(Java Database Connectivity)Java資料庫連接,
二、JDBC流程
1、注冊驅動
// 1、注冊驅動
Class.forName("com.mysql.cj.jdbc.Driver");
2、獲取連接
public class Demo1 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// 1、注冊驅動
Class.forName("com.mysql.cj.jdbc.Driver");
// 2、資料庫連接基本資訊url、user、password
String url = "jdbc:mysql://localhost:3306/seckill?useSSL=false&useUnicode=true&characterEncoding=UTF-8&useAffectedRows=true&nullCatalogMeansCurrent=true&allowMultiQueries=true&serverTimezone=GMT%2B8";
String user = "root";
String password = "123456";
// 3、獲取連接
Connection conn = DriverManager.getConnection(url, user, password);
log.info(">>>>>>>>>>>>【{}】", conn);
}
3、創建Statement或Preparestatement
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
initDataSource();// 初始化連接池
try{// 查詢資料
String sql = "select * from sec_kill";
Statement statement = connection.createStatement();
}catch (Exception e){
log.info(">>>>>>>>>>>>", e);
}
}
注:Preparestatement有預防SQL注入的功效
4、executeQuery或executeUpdate執行查詢/更新
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
initDataSource();// 初始化連接池
try{// 查詢資料
String sql = "select * from sec_kill";
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
long id = rs.getLong("sec_kill_id");
String name = rs.getString("name");
log.info(">>>>>>id:{},name:{}", id, name);
}
}catch (Exception e){
log.info(">>>>>>>>>>>>", e);
}
}
5、涉及事務時(增修改一致性)
5.1、setAutoCommit設定是否自動提交
5.2、commit提交事務
5.3、rollback拋例外手動回滾事務
try {
// 開起事務
conn.setAutoCommit(false);
// 積分扣減
// 下單
// 提交事務
conn.commit();
} catch (Exception e) {
System.out.println(e.getMessage());
// 事務回滾
conn.rollback();
}
注:需要事務在同一個連接上
6、close釋放資源
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
initDataSource();// 初始化連接池
try{// 查詢資料
String sql = "select * from sec_kill";
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
long id = rs.getLong("sec_kill_id");
String name = rs.getString("name");
log.info(">>>>>>id:{},name:{}", id, name);
}
}catch (Exception e){
log.info(">>>>>>>>>>>>", e);
} finally {
connection.close();
statement.close();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/387070.html
標籤:其他
上一篇:Java:注解知識溫顧
下一篇:JAVA知識大考察
