package com.softeem.utils;
import java.sql.Connection;
import com.softeem.utils.DBConnection;
public class BaseConn {
public Connection getConn(){
return new DBConnection().getConn();
}
}
package com.softeem.utils;
import java.util.List;
public interface BaseDAO<T> {
public boolean insert(T t);
public boolean delete(T t);
public boolean update(T t);
public List<T> findAll();
public T findById(T t);
}
package com.softeem.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
//通用增删改
public class DAOHelper {
public static boolean execUpdate(Connection conn, String sql, Object... obj) {
try {
PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
ps.setObject(1 + i, obj[i]);
}
int i = ps.executeUpdate();
return i > 0 ? true : false;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
//通用查
public static <T> List<T> execQuery(String sql,CallBack<T> call,Object...params){
Connection conn = DBConnection.getConn();
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
for(int i = 0; i < params.length;i++){
ps.setObject(i+1, params[i]);
}
ResultSet rs = ps.executeQuery();
return call.getDatas(rs);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static <T> T execQueryOne(String sql,CallBack<T> call,Object...params){
Connection conn = DBConnection.getConn();
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
for(int i = 0; i < params.length;i++){
ps.setObject(i+1, params[i]);
}
ResultSet rs = ps.executeQuery();
return call.getData(rs);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
// public interface CallBack<T>{
// public List<T> getDatas(ResultSet rs);
// }
public static abstract class CallBack<T>{
public List<T> getDatas(ResultSet rs){
return null;
}
public T getData(ResultSet rs){
return null;
}
}
}
package com.softeem.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBConnection {
//声明连接数据库的基本参数
private static final String Driver = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost/ts";
private static final String USER = "root";
private static final String PASSWORD = "123123";
//在静态块中加载驱动,防止反复创建
static{
try {
Class.forName(Driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//封装获取连接的方法
public static Connection getConn(){
try {
return DriverManager.getConnection(URL,USER,PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void close(ResultSet rs,Statement stat,Connection conn){
try {
if(rs != null)rs.close();
if(stat != null)stat.close();
if(conn != null)conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
JDBC的封装
最新推荐文章于 2022-09-26 13:55:13 发布