利用conn.properties配置文件进行数据库连接

来源:互联网 发布:水仙花数的算法流程图 编辑:程序博客网 时间:2024/05/17 19:57

DbUtil.java

public class DbUtil {private String driver;private String url;private String user;private String pass;public void initPara() throws Exception{Properties props = new Properties();props.load(this.getClass().getResourceAsStream("conn.properties"));driver=props.getProperty("driver");    url = props.getProperty("url");    user = props.getProperty("user");    pass = props.getProperty("pass");    Class.forName(driver);}//建立连接public Connection getCon() throws Exception{this.initPara();Connection con = DriverManager.getConnection(url, user, pass);return con;}//关闭连接public void closeCon(Connection con) throws SQLException{if(con != null){con.close();}}//测试public static void main(String[] args){DbUtil dbUtil = new DbUtil();try {dbUtil.getCon();System.out.println("连接成功!!");} catch (Exception e) {// TODO Auto-generated catch blockSystem.out.println("连接失败!");e.printStackTrace();}}}


conn.properties

driver = com.mysql.jdbc.Driverurl = jdbc:mysql://127.0.0.1:3306/数据库名user = rootpass = 123456



原创粉丝点击