在學(xué)習(xí)任何一種ORM的時(shí)候腾降,免不了都要讓我們想起原生態(tài)的JDBC是如何寫的碌奉,因?yàn)橹挥羞@樣你才能感受到為什么要用到新的ORM產(chǎn)品劝贸,
諸如學(xué)習(xí)hibernate等等潮罪。jdbc顧名思義的意思是java的數(shù)據(jù)庫(kù)連接(java database connectity).它是一種執(zhí)行sql的javaAPI康谆,可以為多種數(shù)據(jù)庫(kù)提供統(tǒng)一的訪問基準(zhǔn)并齐。
? 一般執(zhí)行jdbc的流程是這樣的:1坡疼,加載數(shù)據(jù)庫(kù)的驅(qū)動(dòng) 2猴凹,獲得連接 3挂签,向數(shù)據(jù)庫(kù)發(fā)起sql請(qǐng)求 4号涯,獲取返回?cái)?shù)據(jù)庫(kù)處理的結(jié)果 5寄啼,處理數(shù)據(jù)庫(kù)返回的結(jié)果 6璃赡,釋放資源嚼蚀。
? package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class jdbcDemo {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
// 1注冊(cè)驅(qū)動(dòng)
try {
Class.forName("com.mysql.jdbc.Driver");
// 2獲得連接
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "root");
System.out.println("數(shù)據(jù)庫(kù)連接成功导而。忱叭。。");
// 3編寫sql語(yǔ)句
// String sql = "select * from userName where username=?";
String sql = "select * from userName ";
ps = conn.prepareStatement(sql);
// ps.setString(1, "world");
// 4執(zhí)行sql
rs = ps.executeQuery();
// 5處理結(jié)果集
while (rs.next()) {
System.out.println(rs.getString("id") + " "
+ rs.getString("username"));
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 6關(guān)閉資源
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
}
}
}
? 用jdbc編碼的方式的缺點(diǎn)
1今艺,數(shù)據(jù)庫(kù)的連接使用時(shí)就創(chuàng)建 不使用時(shí)就關(guān)閉 每次連接數(shù)據(jù)庫(kù) 對(duì)數(shù)據(jù)庫(kù)進(jìn)行頻繁的操作 導(dǎo)致資源嚴(yán)重被浪費(fèi) 一開一閉
2韵丑,sql語(yǔ)句被寫到j(luò)ava代碼中 如果數(shù)據(jù)庫(kù)表改變了 就必須重新編寫java類
3,設(shè)置參數(shù)比較麻煩虚缎,必須明確知道參數(shù)的位置撵彻,要不然會(huì)出錯(cuò)
4,結(jié)果集處理比較繁瑣 獲取結(jié)果時(shí)存在大量的手工操作实牡,如果一張表有十幾個(gè)字段的話就需要十幾次rs.get語(yǔ)句,造成大量的重復(fù)工作