创建properties格式文件
在eclipse创建properties格式文件,新建信息:
driverClass = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3307/stu
username = root
password = 1234
创建类DBUtil
import java.sql.*;
import java.util.ResourceBundle;
/**
*
* @author cyh
*数据库工具类
*/
public class DBUtil {
private static String driverClass;
private static String url;
private static String username;
private static String password;
static{
ResourceBundle rb = ResourceBundle.getBundle(
"dbinfo");
driverClass = rb.getString(
"driverClass");
url = rb.getString(
"url");
username = rb.getString(
"username");
password = rb.getString(
"password");
try {
Class.forName(driverClass);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection
getConnection()
throws Exception{
return DriverManager.getConnection(url,username,password);
}
public static void closeAll(ResultSet rs , PreparedStatement pre, Connection conn){
if (rs !=
null){
try {
rs.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
if (pre !=
null){
try {
pre.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
if (conn !=
null){
try {
conn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
}
这样以后只需要通过DBUtil的静态方法就可以操作数据库,避免麻烦
知识积累
静态代码块的作用:在类加载的时候执行, 只执行一次 ResourceBundle 用来读取配置文件的信息,通过对象.getString(name) 来获取配置文件的值