zoukankan      html  css  js  c++  java
  • jdbc将数据库连接信息放置配置文件中

    目录如下:

    jdbcConnection.java:

    
    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:

    
    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/test
    user=root
    pwd=root
    

    用Junit测试通过,连接成功。。。

     

  • 相关阅读:
    COMPUTE BY 子句 cube 子句
    性能计数器 可接受值 或者说参考范围
    我们也来hold住优化SQL SERVER锁的使用
    反编译工具源代码
    图片居中,图片垂直居中,图片水平居中
    SessionStateTempDataProvider类需要启用会话状态(2)
    是我Out了,还是IT市场真井喷了?
    四天玩转 Windows Phone 开发
    从物理结构说sql server 优化
    SEO和百度
  • 原文地址:https://www.cnblogs.com/JAYIT/p/4993272.html
Copyright © 2011-2022 走看看