JDBC(Java DataBase Connectivity)
JDBC是用于執(zhí)行SQL語句的Java API,由一組用Java語言編寫的類和接口組成,為多種關(guān)系型數(shù)據(jù)庫提供了統(tǒng)一的訪問基準(zhǔn)。
JDBC隸屬于JavaSE的范疇,伴隨著JavaSE的版本升級。
Java6開始:JDBC4.0開始無需加載注冊驅(qū)動(dòng)。
Java7開始:JDBC4.1提供RowSetProvider工具類
JDBC訪問數(shù)據(jù)庫的形式主要有兩種
直接使用JDBC API去訪問數(shù)據(jù)庫服務(wù)器(MySQL/Oracle)。
間接使用JDBC的API去訪問數(shù)據(jù)庫服務(wù)器
如第三方工具,Hibernate,,MyBatis等(底層依然是JDBC)。
獲取JDBC的連接對象的步驟
1.導(dǎo)入驅(qū)動(dòng)
- 將MySQL的驅(qū)動(dòng)Jar包添加到項(xiàng)目中
MySQL驅(qū)動(dòng)下載地址
2.獲取連接
public static void demo() throws ClassNotFoundException, SQLException {
1.注冊驅(qū)動(dòng)
Class.forName("com.mysql.jdbc.Driver");
2.獲取連接對象
拼接方式:jdbc:使用什么類型的數(shù)據(jù)庫:數(shù)據(jù)庫地址:數(shù)據(jù)庫端口號:哪個(gè)數(shù)據(jù)庫
url = jdbc:mysql://localhost(127.0.0.1):3306/jdbcdemo
user = root 數(shù)據(jù)庫賬號
password = root 數(shù)據(jù)庫密碼
Connection conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/demo",
"root",
"root");
}
3.使用PreparedStatement預(yù)編譯
public static void demo() throws ClassNotFoundException, SQLException {
//?表示占位符
String sql = "SELECT * FROM t_student WHERE id = ?";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/demo",
"root",
"root");
PreparedStatement ps = conn.prepareStatement(sql);
//參數(shù):占位符,對應(yīng)查詢條件
ps.setLong(1, 1L);
//獲取結(jié)果查詢結(jié)果集
ResultSet rs = ps.executeQuery();
while (rs.next()) {
//獲取數(shù)據(jù)
String name = rs.getString("name");
System.out.println(name);
}
}
DDL
創(chuàng)建表
public static void demo() throws ClassNotFoundException, SQLException {
String sql = "CREATE TABLE t_demo(" +
"id BIGINT PRIMARY KEY AUTO_INCREMENT," +
"name VARCHAR(20)," +
"age INT);";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = getConnection();
Statement st = conn.createStatement();
st.executeLargeUpdate(sql);
st.close();
conn.close();
}
public static Connection getConnection() {
try {
return DriverManager
.getConnection("jdbc:mysql://localhost:3306/demo",
"root",
"root");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
DML
插入數(shù)據(jù)
public static void demo() throws ClassNotFoundException, SQLException {
String insertSql = "INSERT INTO t_demo(id,name,age)VALUES(1,'測試',18)";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = getConnection();
Statement st = conn.createStatement();
st.executeLargeUpdate(insertSql);
st.close();
conn.close();
}
修改數(shù)據(jù)
public static void demo() throws ClassNotFoundException, SQLException {
String updateSql = "UPDATE t_demo SET name = '修改',age = 20 WHERE id = 1";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = getConnection();
Statement st = conn.createStatement();
st.executeLargeUpdate(updateSql);
st.close();
conn.close();
}
刪除數(shù)據(jù)
public static void demo() throws ClassNotFoundException, SQLException {
String deleteSql = "DELETE FROM t_demo WHERE id = 1";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = getConnection();
Statement st = conn.createStatement();
st.executeLargeUpdate(deleteSql);
st.close();
conn.close();
}
DQL
public static void demo() throws ClassNotFoundException, SQLException {
//?表示占位符
String sql = "SELECT * FROM t_student WHERE id = ?";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/demo",
"root",
"root");
PreparedStatement ps = conn.prepareStatement(sql);
//參數(shù):占位符,對應(yīng)查詢條件
ps.setLong(1, 1L);
//獲取結(jié)果查詢結(jié)果集
ResultSet rs = ps.executeQuery();
while (rs.next()) {
//獲取數(shù)據(jù)
String name = rs.getString("name");
System.out.println(name);
}
rs.close();
ps.close();
conn.close();
}
Dao設(shè)計(jì)思想和規(guī)范
DAO層在業(yè)務(wù)邏輯與數(shù)據(jù)庫資源中間,是一個(gè)數(shù)據(jù)訪問的接口。
用程序設(shè)計(jì)的語言來說,就是建立一個(gè)接口,將所有對數(shù)據(jù)源的訪問操作,抽象封裝起來。
public interface IStudentDao {
void add(Student student);
void delet(Long id);
void update(Student student);
Student get(Long id);
List<Student> list();
}
分包規(guī)范
com.w.pss.util :工具包,存放工具類
com.w.pss.domian/modle/bean :模型包,存放封裝的對象類
com.w.pss.dao :DAO接口包,存放DAO接口
com.w.pss.impl :接口實(shí)現(xiàn)包,存放接口的實(shí)現(xiàn)類
com.w.pss.test :存放測試類
命名規(guī)范
接口:IXxx,如:IWidget
實(shí)現(xiàn):XxxImpl,如:KeyImpl
測試:XxxTest
Dao:XxxDao
Domain組件的設(shè)計(jì)思想
Domain組件是把數(shù)據(jù)封裝到一個(gè)類中,用來負(fù)責(zé)組件間的數(shù)據(jù)傳遞。
如果方法的形參需要傳遞過多的參數(shù),那就將這些參數(shù)封裝成一個(gè)實(shí)體類傳遞,這個(gè)實(shí)體類即Domain。
void update(Student student);
JDBC的異常處理
傳統(tǒng)方式處理
public static void demo() {
String deleteSql = "DELETE FROM t_demo WHERE id = 1";
Connection conn = null;
Statement st = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/demo",
"root",
"root");
st = conn.createStatement();
st.executeLargeUpdate(deleteSql);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if (conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
}
AutoCloseable處理IO異常
public void testHandlerException() {
String sql = "CREATE TABLE t_demo(
id BIGINT PRIMARY KEY AUTO_INCREMENT,
age INT);";
try (
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/demo",
"root", "root");
Statement st = conn.createStatement();
) {
st.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
事務(wù)
在數(shù)據(jù)庫中,開啟事務(wù)后操作數(shù)據(jù),只要出現(xiàn)一點(diǎn)異常,這組數(shù)據(jù)將不執(zhí)行任何修改提交的操作,反之則完整的執(zhí)行。
極端慘烈的要成功都成功,要失敗都失敗。
事務(wù)相關(guān)細(xì)節(jié)
1.默認(rèn)情況下,事務(wù)在執(zhí)行完DML操作就自動(dòng)提交。
2.查詢操作,其實(shí)是不需要事務(wù)的,但是在開發(fā)中也把查詢放入其中。
3.記得commit()提交事務(wù)。
4.事務(wù)不應(yīng)該在DAO層處理,應(yīng)該在service層控制。
事務(wù)模板
@Test
public void testTx() {
PreparedStatement ps = null;
ResultSet rs = null;
Connection conn = null;
try {
//取消自動(dòng)提交
conn.setAutoCommit(false);
//邏輯語句
//成功后提交
conn.commit();
} catch (Exception e) {
try {
//回滾
conn.rollback();
} catch (SQLException e1) {
throw new RuntimeException(e1);
}
}
}