用配置文件链接数据库
1. Eclipse中,在src目录下创建db.properties文件,在里面配置数据库链接所需的 Driver,url,user,possword ,注意等号左右不能空格
如:
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;databaseName=restrant
user=sa
password=110
2.写一个数据库链接类
ConnDB类
package tools; import java.sql.*; public class ConnDB { public Connection conn = null; public Statement stmt = null; public ResultSet rs = null; public ConnDB(){ } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ public static Connection getConnection() { PropertiesUtils.loadFile("/db.properties"); String url = PropertiesUtils.getPropertyValue("url"); String user = PropertiesUtils.getPropertyValue("user"); String password = PropertiesUtils.getPropertyValue("password"); String driver = PropertiesUtils.getPropertyValue("driver"); Connection conn = null; try { Class.forName(driver); conn = DriverManager.getConnection(url,user,password); } catch (Exception ee) { ee.printStackTrace(); } if (conn == null) { System.err.println("error~~~~~~~~~~~~~~~" ); } return conn; }
PropertiesUtils 类 供读取db.properties
配置文件
package tools; import java.io.IOException; import java.util.Properties; public class PropertiesUtils { //产生一个操做配置文件的对象 static Properties prop = new Properties(); /** * * @param fileName 须要加载的properties文件,文件须要放在src根目录下 * 是否加载成功 */ public static boolean loadFile(String fileName){ try { prop.load(PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName)); } catch (IOException e) { e.printStackTrace(); return false; } return true; } /** * 根据KEY取回相应的value */ public static String getPropertyValue(String key){ return prop.getProperty(key); } }