public class DbUtil {
private static String driver;
private static String jdbcurl;
private static String nm;
private static String pwd;
static{
try {
//声明资源器类 -
Properties prop = new Properties();
//获取这个文件的路径
URL url = DbUtil.class.getClassLoader().getResource("jdbc.properties");
String path = url.getPath();
//为了防止有中文或是空格
path = URLDecoder.decode(path,"UTf-8");
File file = new File(path);
//加载jdbc.properties这个文件
prop.load(new FileInputStream(file));
//获取信息
driver = prop.getProperty("driver");
jdbcurl = prop.getProperty("url");
nm = prop.getProperty("name");
pwd = prop.getProperty("pwd");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection openConnection(){
try {
Class.forName(driver);
return DriverManager.getConnection(jdbcurl, nm, pwd);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void closeConnection(Connection conn){
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
在项目src文件夹创建jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/db909?useUnicode=true&characterEncoding=UTF8
name=root
pwd=123456