Java读写properties文件连接数据库

一、定义properties文件

例如:连接mysql数据库的db.properties

driverName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=root  

例如:连接sqlserver数据库的db.properties

driverName=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;databaseName=MyDB
username=sa
password=123456

二、加载对应驱动程序

网上多的是,略

三、java读取properties文件连接数据库

package util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库连接 && 查询方法定义
 * @author ""
 *
 */
public class JdbcUtil {
	
    private static String dirverName;
    private static String url;
    private static String username;
    private static String password;
    
    static{
        try {
            InputStream inputStream = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            //从输入字节流读取属性列表(键和元素对)
            properties.load(inputStream);
            //用此属性列表中指定的键搜索属性,获取驱动,url,username,password
            dirverName = properties.getProperty("driverName");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            //加载驱动
            Class.forName(dirverName);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     * @return
     */
    public static Connection getConnection() {
    	Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
        	System.out.println("connect database error...");
            e.printStackTrace();
        }
        return conn;
    }
    
    /**
     * 自定义查询方法
     * @param sql
     * @return
     */
  	public static ResultSet select(String sql){
  		ResultSet res = null;
  		PreparedStatement ps =null;
  		try {
  			ps = JdbcUtil.getConnection().prepareStatement(sql);
  			res =  ps.executeQuery();
  		} catch (SQLException e) {
  			System.out.println("select database error...");
  			e.printStackTrace();
  		}
  		return res;
  	}
  	
  	public static void closeConnection(){
  		try {
  			JdbcUtil.getConnection().close();
  		} catch (SQLException e) {
  			System.out.println("database close error...");
  			e.printStackTrace();
  		}
  	}

}

以上这种方式即可实现数据库连接信息在文件中配置,更改数据库的时候只需更改文件即可。

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值