javaweb操作数据库工具类

package com.wang.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
private static String driver;
private static String url;
private static String username;
private static String password;

static {
Properties properties = new Properties();
InputStream io = BaseDao.class.getClassLoader().getResourceAsStream("jdbc.properties");

try {
properties.load(io);
} catch (IOException e) {
e.printStackTrace();
}
driver=properties.getProperty("jdbc.driver");
url=properties.getProperty("jdbc.url");
username=properties.getProperty("jdbc.user");
password=properties.getProperty("jdbc.password");

}

public static Connection getConnection(){
Connection connection=null;
try {
Class.forName(driver);
connection= DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}


return connection;
}

public static ResultSet execute(Connection connection,PreparedStatement pstm,ResultSet resultSet,String sql,Object[] params) throws SQLException {
pstm = connection.prepareStatement(sql);
for (int i = 0; i <params.length ; i++) {
pstm.setObject(i+1,params[i]);

}
resultSet = pstm.executeQuery();
return resultSet;


}


public static int execute(Connection connection,PreparedStatement pstm,String sql,Object[] params) throws SQLException {
pstm = connection.prepareStatement(sql);
for (int i = 0; i <params.length ; i++) {
pstm.setObject(i+1,params[i]);

}
int update = pstm.executeUpdate();
return update;


}

public static boolean closeResource(Connection connection,PreparedStatement pstm,ResultSet resultSet)
{
boolean flag=true;


if (connection!=null)
{
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
flag=false;
}

}
if (pstm!=null)
{
try {
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
flag=false;
}

}
if (resultSet!=null)
{
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
flag=false;
}

}
return flag;
}






}
上一篇:如何通过JDBC访问数据库


下一篇:基于java语言去访问数据库