分享

JDBC---将数据库连接信息放置配置文件中

 昵称14303593 2016-08-28

目录如下:

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/test
user=root
password=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;
	}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多