public class SQLconnection {
/**连接数据库的名字*/ private static String username; /**连接数据库的密码*/ private static String userpwd; /**连接数据库的路径*/ private static String url; /** * 静态初始化块,从Properties文件中获取数据库连接的必要参数*Properties文件中的内容包括有
*url:jdbc:mysql://127.0.0.1:3306/crm\?useUnicode=true&characterEncoding=UTF-8
*name:root*pwd:admin
*/ static{ Properties pro = new Properties(); try { pro.load(new FileInputStream("./src/sql.properties")); url=pro.getProperty("url"); username=pro.getProperty("name"); userpwd=pro.getProperty("pwd"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 联接数据库 * @return 一个数库连接 */ public static Connection getConnection() { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url,username,userpwd); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } /** * 关闭数据库连接 * @param conn 一个数据库连接 */ public static void closeConnection(Connection conn){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}