mysql 之通过配置文件链接数据库
配置文件jdbc.properties
##MySQL driver=com.mysql.jdbc.Driver url=jdbc\:mysql\:///ake?useUnicode\=true&characterEncoding\=UTF-8 username=root password=1234 ##Oracle #driver=oracle.jdbc.driver.OracleDriver #url=jdbc:oracle:thin:@127.0.0.1:1521:orcl #username=scott #password=tiger
简单的讲一下。配置文件写了MySQL和Oracle的数据库信息,我的数据库是mysql 所以我把oracle的配置信息注释掉了。
接下来就是一个单例(饿汉式)的获得数据库连接方法工具类
package Studying.d15; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; public class ConnUtils { private static Connection con = null; static{ try { Properties p = new Properties(); p.load( new FileInputStream("jdbc.properties") ); String driver = p.getProperty("driver"); String url = p.getProperty("url"); String username = p.getProperty("username"); String password = p.getProperty("password"); System.out.println(url+","+driver); Class.forName(driver); con = DriverManager.getConnection(url, username, password); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection(){ return con; } }