抽取jdbc工具类JdbcUtil
1.在src下创建一个jdbc.properties文件
url=jdbc:mysql:///demo
user=root
password=123
driver=com.mysql.jdbc.Driver
2.编写工具类
public class JdbcUtil { private static Connection con = null; private static String url; private static String user; private static String password; private static String driver; static{ Properties p = new Properties();//创建Properties集合对象 InputStream res = JdbcUtil.class //利用类加载器获取到该配置文件,他的默认路径是从src下寻找,返回一个输入流 .getClassLoader() .getResourceAsStream("jdbc.properties"); try { p.load(res); //加载配置文件 url = p.getProperty("url"); //获取配置文件中的值 user = p.getProperty("user"); password = p.getProperty("password"); driver = p.getProperty("driver"); } catch (IOException e) { e.printStackTrace(); } } /** * 获取连接 * @return */ public static Connection getConnection(){ try { Class.forName(driver); con = DriverManager.getConnection(url, user, password); } catch (Exception e) { e.printStackTrace(); } return con; } /** * 关闭连接 * @param stmt * @param con */ public static void close(Statement stmt,Connection con){ if(stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(con!=null){ try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }