java 持久化 jdbc的連接:
對(duì)于連接 準(zhǔn)備好對(duì)應(yīng)數(shù)據(jù)庫(kù)的jar:
java代碼中首先建立三個(gè)對(duì)象:
-
Class.forName(url) url為jar驅(qū)動(dòng)中路徑 比如oracle中:
image.png
來(lái)進(jìn)行加載驅(qū)動(dòng)
- Connection 創(chuàng)建連接
- Statement (PreparedStatement) 通過(guò)statement來(lái)發(fā)起對(duì)于數(shù)據(jù)庫(kù)的操作,PreparedStatement是預(yù)編譯的statement,對(duì)于使用他的好處是 (1)sql注入問(wèn)題
(2) 提高效率 (對(duì)于他的占位符下標(biāo)是 1 開(kāi)始的)
接下來(lái)就是對(duì)于數(shù)據(jù)庫(kù)操作拿到數(shù)據(jù) 對(duì)于數(shù)據(jù)的操作 ,最后記得關(guān)閉資源
具體java代碼 如下:
//用來(lái)連接數(shù)據(jù)庫(kù)的工具類
public class DBUtils {
private static String driver="oracle.jdbc.driver.OracleDriver";
private static String url = "jdbc:oracle:thin:@localhost:1521:xe";
private static String user = "xz";
private static String pwd = "xz";
private static final ThreadLocal<Connection>
threadLocal = new ThreadLocal<Connection>(); //多線程的多對(duì)象耗時(shí)操作
//獲取connection連接對(duì)象
public static Connection getConnection() throws ClassNotFoundException, SQLException{
Connection conn = threadLocal.get();
if(conn==null){
Class.forName(driver);
conn = DriverManager.getConnection(url,user,pwd);
threadLocal.set(conn);
}
return conn;
}
//關(guān)閉connection資源
public static void conClose(){
Connection con = threadLocal.get();
if(con!=null){
threadLocal.set(null);
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//關(guān)閉資源
public static void Close(ResultSet rs,Statement st){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
