1、什麼是JDBC
JDBC(Java Data Base Connectivity,java資料庫連接配接)是一種用于執行SQL語句的Java API,是用Java語言編寫的類和接口組成的,可以為多種關系型資料庫提供統一通路的接口。JDBC提供了一種基準,說白了,也就是sun公司為各大資料庫廠商的關系型資料庫連接配接java所制定的規範,是以他們隻需要實作JDBC的接口規範即可,而具體的實作是由各大資料庫廠商去實作的,由于每種資料庫的獨特性,Java是無法控制的,是以JDBC是一種典型的橋接模式。我們據此也可以建構更進階的工具和接口,比如封裝常用的CRUD工具類,使資料庫開發人員能夠更快速、高效、簡便的開發資料庫應用程式。
- 從層次上看,JDBC是較底層的持久層操作方式,而Hibernate和MyBatis都是在JDBC的基礎上進行了封裝使其更加友善程式員對持久層的操作。
- 從功能上看,JDBC就是簡單的建立資料庫連接配接,然後建立statement,将sql語句傳給statement去執行,如果是有傳回結果的查詢語句,會将查詢結果放到ResultSet對象中,通過對ResultSet對象的周遊操作來擷取資料;Hibernate是将資料庫中的資料表映射為持久層的Java對象,對sql語句進行修改和優化比較困難;MyBatis是将sql語句中的輸入參數和輸出參數映射為java對象,sql修改和優化比較友善。
- 從使用上看,如果進行底層程式設計,而且對性能要求極高的話,應該采用JDBC的方式;如果要對資料庫進行完整性控制的話建議使用Hibernate;如果要靈活使用sql語句的話建議采用MyBatis架構。
使用JDBC進行CRUD操作
/**
*
* @description: JDBC連接配接MySQL資料庫進行CRUD操作
*
* 步驟:
* 1、加載驅動和注冊資料庫資訊。
* 2、打開Connection,擷取PreparedStatement對象。
* 3、通過PreparedStatement執行SQL,傳回結果到ResultSet對象。
* 4、使用ResultSet讀取資料,然後通過代碼轉換為具體的POJO對象。
* 5、關閉資料庫相關資源,先開的後關,後開的先關。
*
* @author: liuhongwei
*/
public class JdbcTest {
private Logger logger = LoggerFactory.getLogger(getClass());
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc://mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";
private static final String USERNAME = "root";
private static final String PASSWORD = "root";
private Connection getConnection() {
Connection conn = null;
try {
// 加載驅動和注冊資料庫資訊
Class.forName(JDBC_DRIVER);
DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
logger.info("Class={JdbcTest.class.getName()} not found", JdbcTest.class.getName(), e);
}
return conn;
}
/**
*
* @description: 儲存使用者資訊
* @param user
* @return
*/
public int save(User user) {
Connection conn = getConnection();
int row = ;
// 5個問号(占位符)代表5個字段預先要保留的值
String sql = "insert into tb_user (username,password,name,sex,email,tel) values(?,?,?,?,?,?)";
PreparedStatement ps = null;
try {
/**
* 使用PreparedStatement的優點:
* 1、具有預編譯功能,相同的SQL語句隻需要編譯一次,提高執行效率。
* 2、可以防止SQL語句注入,提高安全性
*/
// 使用PreparedStatement對象裡來建構并執行SQL語句
ps = conn.prepareStatement(sql);
// 通過PreparedStatement對象裡的set方法設定要插入的值
ps.setString(, user.getUsername());
ps.setString(, user.getPassword());
ps.setString(, user.getName());
ps.setInt(, user.getSex());
ps.setString(, user.getEmail());
ps.setString(, user.getTel());
// 傳回影響行數
row = ps.executeUpdate();
} catch (SQLException e) {
logger.info("Bad SQL Grammer", e);
} finally {
close(null, ps, conn);
}
return row;
}
/**
*
* @description: 修改使用者資訊
* @param user
* @return
*/
public int update(User user) {
Connection conn = getConnection();
int row = ;
String sql = "update tb_user set password=? where username=?";
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
ps.setString(, user.getPassword());
ps.setString(, user.getUsername());
row = ps.executeUpdate();
} catch (SQLException e) {
logger.info("Bad SQL Grammer", e);
} finally {
close(null, ps, conn);
}
return row;
}
/**
*
* @description: 根據id删除使用者
* @param id
* @return
*/
public int delete(Long id) {
Connection conn = getConnection();
int row = ;
String sql = "delete from tb_user where id='" + id + "'";
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
row = ps.executeUpdate();
} catch (SQLException e) {
logger.info("Bad SQL Grammer", e);
} finally {
close(null, ps, conn);
}
return row;
}
/**
*
* @description: 根據id查詢使用者資訊
* @param id
* @return
*/
public User getAll(Long id) {
Connection conn = getConnection();
String sql = "select id,username,password,name,sex,email,tel from tb_user where id = ?";
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
ps.setLong(, id);
// 通過PreparedStatement執行Sql,傳回結果到ResultSet對象
rs = ps.executeQuery();
// 周遊結果集
while (rs.next()) {
Long userId = rs.getLong("id");
String username = rs.getString("username");
String password = rs.getString("password");
String name = rs.getString("name");
Integer sex = rs.getInt("sex");
String email = rs.getString("email");
String tel = rs.getString("tel");
User user = new User();
user.setId(userId);
user.setUsername(username);
user.setPassword(password);
user.setName(name);
user.setSex(sex);
user.setEmail(email);
user.setTel(tel);
return user;
}
} catch (SQLException e) {
logger.info("Bad SQL Grammer", e);
}
return null;
}
/**
*
* @description: 釋放資源,注意:先開的後關,後開的先關
* @param rs
* @param ps
* @param conn
*/
public void close(ResultSet rs, PreparedStatement ps, Connection conn) {
try {
if (rs != null && rs.isClosed()) {
rs.close();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
if (ps != null && ps.isClosed()) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null && conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}