用配置文件鏈接數據庫
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); } }