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();
}
}
}
}
}
}
}
}