java 持久化 jdbc的連接:
對于連接 準(zhǔn)備好對應(yīng)數(shù)據(jù)庫的jar:
java代碼中首先建立三個(gè)對象:
-
Class.forName(url) url為jar驅(qū)動(dòng)中路徑 比如oracle中:
image.png
來進(jìn)行加載驅(qū)動(dòng)
- Connection 創(chuàng)建連接
- Statement (PreparedStatement) 通過statement來發(fā)起對于數(shù)據(jù)庫的操作,PreparedStatement是預(yù)編譯的statement,對于使用他的好處是 (1)sql注入問題
(2) 提高效率 (對于他的占位符下標(biāo)是 1 開始的)
接下來就是對于數(shù)據(jù)庫操作拿到數(shù)據(jù) 對于數(shù)據(jù)的操作 ,最后記得關(guān)閉資源
具體java代碼 如下:
//用來連接數(shù)據(jù)庫的工具類
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>(); //多線程的多對象耗時(shí)操作
//獲取connection連接對象
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();
}
}
}
}
