通过文件中配置信息创建数据库连接

通过文件中配置信息创建数据库连接

如果像文章 http://blog.csdn.net/xiaolangfanhua/article/details/52476211 中所述那样,每次要连接数据库时都手动设置 drivers 、url 、username 、password等信息是非常繁琐的,而且还容易出错,我们可以把这些信息以properties的形式配置创建在一个properties的文件中,这样每次要连接数据库时直接在文件中读取这些信息,既方便又不容易出错。

首先配置properties文件:

文件中需要配置的量有:drivers 、url 、username 、password
例如:
1、文件内容:

jdbc.drivers=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/publicationdb? user=root&password=123456
jdbc.username=root
jdbc.password=123456

2、文件路径:

“F:\Projects\Mysql\database.properties”
这个路径在连接的时候需要用到。

以此创建数据库连接并进行操作的实例代码如下:

import java.nio.file.*;
import java.io.*;
import java.util.*;
import java.sql.*;

public class TestDB {
    /*
     * 用于在database.properties 文件中读取链接参数,连接到数据库
     * 并执行相关数据库语言,创建数据库
     */

    public static void main(String[] args) throws IOException
    {
        // TODO Auto-generated method stub

        try{
            runTest();
        }catch(SQLException ex){
            for(Throwable t:ex)
            {
                t.printStackTrace();
            }
        }
    }

    public static void runTest() throws SQLException, IOException 
    {
        try(Connection conn=getConnection())
        {
            Statement stat=conn.createStatement();

            stat.executeUpdate("CREATE TABLE Greetings (Message CHAR(20))");
            stat.executeUpdate("INSERT INTO Greetings VALUES('Hello, World!')");

            try(ResultSet result=stat.executeQuery("SELECT * FROM Greetings"))
            {
                if(result.next())
                {
                    System.out.println(result.getString(1));
                }
                stat.executeUpdate("DROP TABLE Greetings");
            }
        }

    }

    public static Connection getConnection() throws IOException, SQLException 
    {
        Properties props=new Properties();
        try(InputStream in=Files.newInputStream(Paths.get("F:\\Projects\\Mysql\\database.properties")))
        {
            props.load(in);
        }
        String drivers=props.getProperty("jdbc.drivers");
        if(drivers!=null) System.setProperty("jdbc.drivers",drivers);
        String url=props.getProperty("jdbc.url");
        String username=props.getProperty("jdbc.username");
        String password=props.getProperty("jdbc.password");

        return DriverManager.getConnection(url,username,password);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值