打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
JDBC---将数据库连接信息放置配置文件中
目录如下:
jdbcConnection.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package jdbc01;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.util.Properties;
import org.junit.Test;
/**
* 将jdbc连接解耦,放入配置文件中
* @author sawshaw
*
*/
public class jdbcConnection{
public static void main(String[] args) {
}
public Connection getConnection() throws Exception{
String driverClass=null;
String jdbcUrl=null;
String user=null;
String pwd=null;
InputStream in=getClass().getClassLoader().getResourceAsStream("jdbc01/sql.properties");
//System.out.println("文件地址:"+getClass().getClassLoader().getResource("jdbc01/sql.properties"));
//System.out.println("文件地址:"+getClass().getClassLoader().getSystemResource("jdbc01/sql.properties"));
Properties properties=new Properties();
properties.load(in);
driverClass=properties.getProperty("driver");
jdbcUrl=properties.getProperty("url");
user=properties.getProperty("user");
pwd=properties.getProperty("pwd");
//forName 返回一个类,newInstance创建一个对象
Driver driver=(Driver) Class.forName(driverClass).newInstance();
Properties info=new Properties();
info.put("user",user);
info.put("password",pwd);
Connection connection=driver.connect(jdbcUrl, info);
return connection;
}
@Test
public void testConnection() throws Exception{
System.out.println(getConnection());
}
}
sql.properties:
1
2
3
4
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
user=root
pwd=root
用Junit测试通过,连接成功。。。
url=jdbc\:mysql\://localhost\:3306/testuser=rootpassword=yongqiang
将上面的Java 方法改写为如下代码:
/** 返回一个与特定数据库的连接 */ public Connection getConnection() { try { //加载属性文件,读取数据库连接配置信息 Properties pro = new Properties(); try { pro.load(JDBC_BaseDAO.class.getResourceAsStream("/db.properties")); } catch (IOException e) { System.out.println("未找到配置文件!!!"); } String url = pro.getProperty("url"); String user = pro.getProperty("user"); String password = pro.getProperty("password"); connection = DriverManager.getConnection(url, user, password); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return connection; }
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
通过读取properties文件的方式来建立JDBC数据源连接
MySQL数据库详解
java 三种读取配置文件的方式
读取properties文件的6种方式,建议收藏!
用jdbc.properties文件配置连接数据库 心得
Java解析resources文件夹下properties文件、连接数据库
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服