连接数据库和关闭数据库
连接数据库
public Connection getConnection(){
try {
Class.forName(driver);
connection= DriverManager.getConnection(url,jdbcuser,pwd);
}catch (Exception e){
e.printStackTrace();
}
return connection;
}
关闭数据库
public void closeResouce(ResultSet resultSet, PreparedStatement preparedStatement,Connection connection){
if (resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement!=null){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
实现增删改的basedao封装
public int executeUpdate(String sql,Object[] params){
DBUtil db=new DBUtil();
int num=0;
Connection connection=db.getConnection();
try {
java.sql.PreparedStatement preparedStatement=connection.prepareStatement(sql);
if (params!=null){
for (int i=0;i<params.length;i++){
preparedStatement.setObject((i+1),params[i]);
}
}
num=preparedStatement.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}
return num;
}
实现查询的BaseDao封装
public ResultSet executeQuery(String sql,Object[] params){
DBUtil db=new DBUtil();
ResultSet resultSet=null;
Connection connection=db.getConnection();
try {
PreparedStatement preparedStatement= (PreparedStatement) connection.prepareStatement(sql);
if (params!=null){
for (int i=0;i<params.length;i++){
preparedStatement.setObject((i+1),params[i]);
}
}
resultSet=preparedStatement.executeQuery();
}catch (Exception e){
e.printStackTrace();
}
return resultSet;
}
获取db.propertues资源,static表示一打开就会自动加载
static {
try {
properties.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
driver=properties.getProperty("driver");
url=properties.getProperty("url");
jdbcuser=properties.getProperty("jdbcuser");
pwd=properties.getProperty("pwd");
} catch (IOException e) {
e.printStackTrace();
}
}
解决维护性功能properties
private static String driver;
private static String url;
private static String jdbcuser;
private static String pwd;
public Connection connection=null;
public static Properties properties=new Properties();