JAVA JDBC 常规增删改查简单封装,可满足大多基本要求
作用:
1, 查询列表是直接返回List对象,不必再遍历;
2, 单条查询直接返回对象;
3, 执行sql仅需一个方法搞定;
package com.Main.Tools;
import com.Main.DB.MySql.DBUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Description: JDBC辅佐工具类
* @author: Adobe Chow
* @date: 2018/12/29 16:02
* @Copyright: www.winshang.com Inc. All rights reserved.
*/
public class SqlUtils {
private static final String LogName = "SqlUtils----> ";
/**
* 执行sql
* @param conn
* @param sql
* @param args
* @throws SQLException
*/
public static void execute(Connection conn,String sql,Object ...args) throws SQLException {
PreparedStatement ptmt = null;
ptmt = conn.prepareStatement(sql);
String para = setParam(ptmt,args);
System.out.println(LogName+"sql: "+sql);
System.out.println(LogName+"参数: "+para);
ptmt.execute();
ptmt.close();
System.out.println(LogName+"执行成功!");
}
/**
* 查询列表
* @param conn
* @param sql
* @param args
* @return
* @throws SQLException
*/
public static List> findList(Connection conn,String sql,Object...args) {
List> list = new ArrayList<>();
PreparedStatement ptmt = null;
try {
ptmt = conn.prepareStatement(sql);
System.out.println(LogName+"sql: "+sql);
String para = setParam(ptmt,args);
System.out.println(LogName+"sql: "+sql);
System.out.println(LogName+"参数: "+para);
ResultSet resultSet = ptmt.executeQuery();
ResultSetMetaData rsmd=resultSet.getMetaData();
while (resultSet.next()){
Mapmap = new HashMap<>();
for(int i=0;ifindFirst(Connection conn,String sql,Object...args) {
List> list = findList(conn,sql+" limit 1",args);
return list==null?null:list.get(0);
}
/**
* 设置参数
* @param ptmt
* @param args
* @return
*/
private static String setParam(PreparedStatement ptmt, Object[] args) throws SQLException {
//加入参数
String parasStr = "";
if (args!=null){
for(int i=0;i> list = findList(DBUtil.getConnection(),"select * from biz_t_error LIMIT 100",null);
for (int i=0;imap = findFirst(DBUtil.getConnection(),"select * from biz_t_error order by addtime desc",null);
System.out.println( "单条记录: "+ map.get("uid")+" "+map.get("errMsg") );
}
}