4天貫通JDBC技術(shù)

二、獲取數(shù)據(jù)庫連接

//獲取數(shù)據(jù)庫的連接

public static Connection getConnection() throws Exception{

//1.獲取數(shù)據(jù)庫連接的基本信息

//1.1創(chuàng)建Properties的對象,以流的形式,將配置文件中的基本信息讀入程序

Properties info = new Properties();

info.load(new FileInputStream("jdbc.properties"));

//1.2提供4個基本信息:url、driverClass、user、password

String url = info.getProperty("url");

String driverClass = info.getProperty("driverClass");

String user = info.getProperty("user");

String password = info.getProperty("password");

//2.加載驅(qū)動

Class.forName(driverClass);

//3.使用DriverManager的getConnection(url,user,password)方法

Connection conn = DriverManager.getConnection(url, user, password);

 

return conn;

}

 

public static void close(ResultSet rs,Statement st,Connection conn){

 

if(rs != null){

try {

rs.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

 

if(st != null){

try {

st.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

if(conn != null){

try {

conn.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

 

【jdbc.properties】

url=jdbc:mysql://127.0.0.1:3306/test

user=root

password=123456

driverClass=com.mysql.jdbc.Driver

 

#user=scott

#password=tiger

#url=jdbc:oracle:thin:@127.0.0.1:1521:orcl

#driverClass=oracle.jdbc.driver.OracleDriver

?

 

本教程由尚硅谷教育大數(shù)據(jù)研究院出品,如需轉(zhuǎn)載請注明來源,歡迎大家關(guān)注尚硅谷公眾號(atguigu)了解更多。