Java 连接数据库操作

上个月正好完成openTCS添加数据库支持这个小项目,今天有空,将自己写的java操作数据库的代码发表出来,如果觉得对大家有用就给个好评。多余的话不说了,上代码。

/**
 *
 * @author Li
 * @data 2023-04-02
 */
public class DataSourceUtil {
  

    private DataSourceUtil() {

    }

    public static DataSource getDruidDataSource() {
           DataSource dataSource =null;
           try {
              InputStream in = DataSourceUtil.class.getClassLoader().getResourceAsStream("db\\dataSource.properties");
               Properties pro = new Properties();
               pro.load(in);
               dataSource = DruidDataSourceFactory.createDataSource(pro);
            System.out.println( "get dataSource : "+ dataSource);
        } catch (Exception var1) {
            var1.printStackTrace();
        }
           return dataSource;
    }


/**
 *
 * @author Li
 * @data 2023-04-02
 */
@SuppressWarnings("unchecked")
public class JdbcTools {
  private static DataSource dataSource;
  private static ThreadLocal<Connection> threadLocal;
  private static PreparedStatement psmt;
  private static ResultSet rs;
  private static Connection conn;

  static {
    try {
      dataSource = DataSourceUtil.getDruidDataSource();
      threadLocal = new ThreadLocal<>();
    } catch (Exception var1) {
      var1.printStackTrace();
    }
  }

  public JdbcTools() {

  }
//获得连接
  protected static Connection getConn() {
    conn = threadLocal.get();
    if (conn == null) {
      //创建连接对象
      try {
        conn = dataSource.getConnection();
        System.out.println("打印出连接:" + conn);
        threadLocal.set(conn);
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
    return conn;
  }
 
  protected static void close(ResultSet rs, PreparedStatement psmt, Connection conn) {
    try {
      if (rs != null) {
        rs.close();
      }
      if (psmt != null) {
        psmt.close();
      }
      if (conn != null && !conn.isClosed()) {
        conn.close();
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  //给预处理命令对象设置参数
  private static void setParams(PreparedStatement psmt, Object... params) throws SQLException {
    if (params != null && params.length > 0) {
      for (int i = 0; i < params.length; i++) {
        psmt.setObject(i + 1, params[i]);
      }
    }
  }
  /**
   *执行添加与更新操作
   */
  public static int executeUpdate(String sql, Object... params) {
    boolean insertFlag ;
    insertFlag = sql.trim().toUpperCase().startsWith("INSERT");
    try {
      conn = getConn();
      if (insertFlag) {
        psmt = conn.prepareStatement(sql,        Statement.RETURN_GENERATED_KEYS);
      } else {
        psmt = conn.prepareStatement(sql);
      }
      setParams(psmt, params);
      int count = psmt.executeUpdate();
      rs = psmt.getGeneratedKeys();
      if (rs.next()) {
        return ((Long) rs.getLong(1)).intValue();
      }
       System.out.println("data update success !! "+count);
      return count;
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return 0;
  }

  private static <T> void setValue(T obj, String property, Object propertyValue) {
    Class<?> clazz = obj.getClass();
    try {
      Field field = clazz.getDeclaredField(property);
      if (field != null) {
        field.setAccessible(true);
        field.set(obj, propertyValue);
      }
    } catch (NoSuchFieldException | IllegalAccessException e) {
      e.printStackTrace();
    }
  }

  public static Object[] executeCountQuery(String sql, Object... params) {
    try {
      conn = getConn();
      psmt = conn.prepareStatement(sql);
      setParams(psmt, params);
      rs = psmt.executeQuery();

      ResultSetMetaData rsmd = rs.getMetaData();

      int columnCount = rsmd.getColumnCount();
      Object[] columnValueArr = new Object[columnCount];

      if (rs.next()) {
        for (int i = 0; i < columnCount; i++) {
          Object columnValue = rs.getObject(i + 1);
          columnValueArr[i] = columnValue;
        }
        return columnValueArr;
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return null;
  }
/**
 *获取单行记录
 */
  public static <T> T getBean(String sql, Class<T> type, Object... params)  {
    T t;
    conn = getConn();
    t = beanHandler(conn, sql, type, params);
    return t;
  }
/**
 * 获取多行记录
 */
  public static <T> List<T> getBeanList(String sql, Class<T> type, Object... params) {
    List<T> list;
    conn = getConn();
    list = beansHandler(conn, sql, type, params);
    return list;
  }

  private static <T> T beanHandler(Connection conn, String sql, Class<T> type, Object... params) {
    T entity = null;
    try {
      psmt = conn.prepareStatement(sql);
      setParams(psmt, params);
      rs = psmt.executeQuery();

      ResultSetMetaData rsmd = rs.getMetaData();

      int columnCount = rsmd.getColumnCount();
      entity = type.getDeclaredConstructor().newInstance();
      if (rs.next()) {
        for (int i = 0; i < columnCount; i++) {
          String columnName = rsmd.getColumnName(i + 1);
          Object columnValue = rs.getObject(i + 1);
          setValue(entity, columnName, columnValue);
        }
      }
    } catch (SQLException | InstantiationException | IllegalAccessException |InvocationTargetException |NoSuchMethodException  e) {
      throw new RuntimeException(e);
    }
    return entity;
  }

  private static <T> List<T> beansHandler(Connection conn, String sql, Class<T> type, Object... params) {
    List<T> list = new ArrayList<>();
    try {
      psmt = conn.prepareStatement(sql);
      setParams(psmt, params);
      rs = psmt.executeQuery();

      ResultSetMetaData rsmd = rs.getMetaData();

      int columnCount = rsmd.getColumnCount();

      while (rs.next()) {
        T entity = type.getDeclaredConstructor().newInstance();
        for (int i = 0; i < columnCount; i++) {
          String columnName = rsmd.getColumnName(i + 1);
          Object columnValue = rs.getObject(i + 1);
          setValue(entity, columnName, columnValue);
        }
        list.add(entity);
      }
    } catch (SQLException | InstantiationException | IllegalAccessException |InvocationTargetException |NoSuchMethodException  e) {
      throw new RuntimeException(e);
    }
    return list;
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值