为了使代码灵活切易于扩展和维护,我们一般将数据库配置信息放入文件中,比如:db.properties
url=jdbc:mysql://localhost:3306/day17
user=root
password=root
driverClass=com.mysql.jdbc.Driver
这时候使用类路径读取:
InputStream in = JdbcUtil.class.getResourceAsStream("/db.properties");
“/”表示classpath的根目录(maven项目中放在resource目录下即可,因为项目打包资源文件放在class下)
代码如下:
public class JdbcUtil {
private static String url = null;
private static String user = null;
private static String password = null;
private static String driverClass = null;
static{
try {
Properties prop = new Properties();
InputStream in = JdbcUtil.class.getResourceAsStream("/bd.properties");
prop.load(in);
//读取配置信息
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("password");
driverClass = prop.getProperty("driverClass");
//加载驱动
Class.forName(driverClass);
} catch (IOException e) {
e.printStackTrace();
System.out.println("读取配置文件失败");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("加载驱动失败");
}
}
/**
* 连接
*/
public static Connection getConnection(){
try {
Connection con = DriverManager.getConnection(url, user, password);
return con;
} catch(SQLException e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 查询
*/
public static void queryall(){
try {
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 查询
*/
public static void insert(Object obj){
try {
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 释放资源的方法
*/
public static void close(Connection conn, Statement stmt){
try{
if(stmt!=null){
stmt.close();
stmt = null;
}
} catch(SQLException e){
e.printStackTrace();
}finally{
try{
if(conn!=null){
conn.close();
conn = null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
public static void close(Connection conn, Statement stmt, ResultSet rs){
try{
if(rs!=null){
rs.close();
rs = null;
}
} catch(SQLException e){
e.printStackTrace();
}finally {
close(conn, stmt);
}
}
}