public class DBUtils {
static private Connection conn;
static private PreparedStatement pstmt;
static private ResultSet rs;
// 使用单例模式实现的数据库Connection方法
static public Connection getConnection() {
try {
if (conn == null) {// 若是已经存在一个connection的实例化对象,则直接使用,避免大量建立多余对象浪费系统资源
Properties properties = new Properties();// 实例化一个properties加载相应数据库的配置信息
properties.load(DBUtils.class.getResourceAsStream("properties文件路径"));
String driver = properties.getProperty("driverClassName");
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
Class.forName(driver);// 加载数据库驱动
conn = DriverManager.getConnection(url, username, password);// 创建数据库链接
}
return conn;
} catch (Exception e) {
System.out.println("链接数据库不成功" + e.getMessage());
}
return null;
}
// 实现基本的数据库增删改操做
public int update(String sql, Object... obj) {
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);// 构建Statement查询语句
for (int i = 0; i < obj.length; i++) {
pstmt.setObject(1 + i, obj[i]);
}
int i = pstmt.executeUpdate();// 执行Statement语句
return i;// 返回操做影响响应表的行数
} catch (Exception e) {
System.out.println("更新数据失败");
}
return 0;
}
// 实现数据库的查询操做,这里以将查询结果构形成一个Map键值对的形式并存入List线性表中为例
public List<Map<String, Object>> query(String sql, Object... obj) {
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
pstmt.setObject(1 + i, obj[i]);
}
rs = pstmt.executeQuery();
////////////////////////
ArrayList<Map<String, Object>> arrayList = new ArrayList<Map<String, Object>>();
ResultSetMetaData metaData = rs.getMetaData();//得到数据库中相应表结构
while (rs.next()) {
Map<String, Object> map = new HashMap<String, Object>();
for (int i = 0; i < metaData.getColumnCount(); i++) {
map.put(metaData.getColumnLabel(i + 1), rs.getObject(i + 1));
}
arrayList.add(map);
}
return arrayList;
///////////////////////
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
// 关闭数据库链接,数据库链接的关闭应该自低向上依次关闭
public void close() {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
if (conn != null)
conn.close();
} catch (Exception e) {
System.out.println("关闭失败");
}
}
}