class="properties">jdbc:sqlserver://localhost:1433; databaseName=stufeedb; integratedSecurity=true; user=sa; password=svse;
?
package com.singlee.dao; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; public class DBHelper { public static Connection conn = null; /** * 获取连接 通过配置文件的方式获取数据库连接,使JDBC操作数据库具有一定的灵活性 */ public DBHelper() { Properties pro = new Properties(); try { // 读取配置文件 pro.load(DBHelper.class .getResourceAsStream("jdbc_sqlserver.properties")); String Driver = pro.getProperty("Driver"); String url = pro.getProperty("url"); String user = pro.getProperty("user"); String password = pro.getProperty("password"); // 加载驱动 Class.forName(Driver); // 获取连接 conn = DriverManager.getConnection(url, user, password); } catch (Exception e) { e.printStackTrace(); } } /** * 关闭连接,节约资源 */ public static void close() { try { if (conn != null) { conn.close(); } } catch (Exception e) { e.printStackTrace(); } } /** * 获取数据库连接 * * @return */ public static Connection getConn() { new DBHelper(); return conn; } }
?