package com.lemon.utils;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;

/**
 * @program: Lemon
 * @description:
 * @author: ray
 * @create: 2022-09-27 14:20
 **/
public class SqlUtils {

    /**
     * 传入sql语句执行sql查询，并且返回查询结果
     *
     * @param sql
     * @return
     */
    public static Object querySingle(String sql) {
        Object result = null;
        Connection conn = null;
        //如果sql语句为空直接返回为空
        if (StringUtils.isBlank(sql)) {
            return null;
        }
        try {
            //创建queryRunner对象
            QueryRunner runner = new QueryRunner();
            //调用查询方法，传入数据库连接、SQL语句、返回值类型
            conn = JDBCUtils.getConnection();
            // 查询操作，使用query
            result = runner.query(conn, sql, new ScalarHandler<>());
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(conn);
        }
        return result;
    }


}
