定义一个properites
dbUrl=jdbc:mysql://localhost:3306/db_news
dbUserName=root
dbPassword=123456
jdbcName=com.mysql.jdbc.Driver
定义一个PropertiesUtil类
package com.news.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesUtil {
public static String getValue(String key) {
Properties prop=new Properties();
InputStream in=new PropertiesUtil().getClass().getResourceAsStream("/news.properties");
try {
prop.load(in);
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return prop.getProperty(key);
}
DbUtil类
package com.news.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbUtil {
public Connection getCon() throws Exception{
Class.forName(PropertiesUtil.getValue("jdbcName"));
Connection con=DriverManager.getConnection(PropertiesUtil.getValue("dbUrl"), PropertiesUtil.getValue("dbUserName"), PropertiesUtil.getValue("dbPassword"));
return con;
}
public void closeCon(Connection con)throws Exception{
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 自动生成的 catch 块
e.printStackTrace();
}
}
}