java的dbhelper类_java 的DBHelper类型

本文介绍了一个用于Java应用程序的数据库帮助类库,该类库提供了连接数据库、执行SQL更新和查询的功能。它使用了PreparedStatement来防止SQL注入,并且能够通过传递RowMapper实现灵活的数据映射。
摘要由CSDN通过智能技术生成
package com.self.util;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

public class DBHelper {

private static String DRIVER ="com.mysql.jdbc.Driver";

private static String URL = "jdbc:mysql:///mydb";

private static String USER ="root";

private static String PASSWORD = "a";

public Connection getConnnection(){

Connection conn = null;

try {

Class.forName(DRIVER);

conn = DriverManager.getConnection(URL, USER, PASSWORD);

} catch (Exception e) {

e.printStackTrace();

}

return conn;

}

public int executeUpdate(String sql, Object...objs) throws SQLException{

int res = 0;

Connection conn = getConnnection();

PreparedStatement stat = conn.prepareStatement(sql);

for (int i=0; i

stat.setObject(i+1, objs[i]);

}

res = stat.executeUpdate();

close(stat, conn);

return res;

}

public T executeQueryForOject(String sql, RowMapper rowMapper, Object...objs){

Connection conn = getConnnection();

PreparedStatement stat = null;

ResultSet rs = null;

T t = null;

try {

stat = conn.prepareStatement(sql);

for (int i=0; i

stat.setObject(i+1, objs[i]);

}

rs = stat.executeQuery();

if (rs.next()){

try {

t = rowMapper.mapRow(rs);

} catch (Exception e) {

e.printStackTrace();

}

}

} catch (SQLException e) {

e.printStackTrace();

}

return t;

}

public ListexecuteQuery(String sql, RowMapper rowMapper, Object... objs){

Connection conn = getConnnection();

PreparedStatement stat = null;

ResultSet rs = null;

List list = new ArrayList();

try {

stat = conn.prepareStatement(sql);

for (int i=0; i

stat.setObject(i+1, objs[i]);

}

rs = stat.executeQuery();

while(rs.next()){

T t;

try {

t = rowMapper.mapRow(rs);

list.add(t);

} catch (Exception e) {

e.printStackTrace();

}

}

} catch (SQLException e) {

e.printStackTrace();

}

return list;

}

private void close(PreparedStatement stat, Connection conn) {

close(null, stat, conn);

}

private void close(ResultSet rs, PreparedStatement stat, Connection conn) {

if (rs != null){

try {

rs.close();

} catch (SQLException e) {

e.printStackTrace();

}finally{

if (stat != null){

try {

stat.close();

} catch (SQLException e) {

e.printStackTrace();

}finally{

if (conn != null){

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值