4天贯通JDBC技术

二、获取数据库连接

//获取数据库的连接

public static Connection getConnection() throws Exception{

//1.获取数据库连接的基本信息

//1.1创建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.加载驱动

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

 

 

本教程由尚硅谷教育大数据研究院出品,如需转载请注明来源,欢迎大家关注尚硅谷公众号(atguigu)了解更多。