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 block
System.out.println("连接失败!");
e.printStackTrace();
}
}
}
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://127.0.0.1:3306/数据库名
user = root
pass = 123456