用jdbc连接mysql时有大量的重复操作,可以抽取出一个工具类
用,properties配置文件存储驱动参数,文件如下
driverclass = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mybase
username = root
password =123
程序如下
package DBUTILSDemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;
public class jdbcUtils {
//连接参数
static final String DRIVERCLASS;
static final String URL;
static final String PASSWORD;
static final String USERNAME;
//获取配置文件信息,注册驱动,用静态代码块,只需要注册一次
static{
//获取。properyies对象
ResourceBundle bundle = ResourceBundle.getBundle("JDBC");
//获取参数
DRIVERCLASS = bundle.getString("driverclass");
URL = bundle.getString("url");
PASSWORD = bundle.getString("password");
USERNAME = bundle.getString("username");
try {
//注册驱动
Class.forName(DRIVERCLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException{
//获得连接
return DriverManager.getConnection(URL,USERNAME,PASSWORD);
}
}