美文网首页
封装从配置文件中读取数据连接数据库取数据

封装从配置文件中读取数据连接数据库取数据

作者: 青风飞絮 | 来源:发表于2019-07-29 17:59 被阅读0次

1.封装的参照代码如下:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JDBCUtils {

    /**
     * @param env 查询的数据库环境,用来识别读ini配置文件的。例如:dev sit
     * @return connection 返回数据连接
     */
    public static Connection getConnection(String env) {
        Connection connection = null;
        String driverName = "";
        String url = "";
        String userName = "";
        String password = "";
        try {
            IniReader reader = new IniReader("src/test/resources/mysql/mysql.ini");
            driverName = reader.getValue(env,"name");
            url = reader.getValue(env,"url");
            userName = reader.getValue(env,"userName");
            password = reader.getValue(env,"password");
            Class.forName(driverName);
            connection = DriverManager.getConnection(url,userName,password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * @param env 查询的数据库环境,用来识别读ini配置文件的。例如:dev sit
     * @param sql 查询的sql语句
     * @param columnLabel 想要获取的列字段的值的列字段名,可变参数
     * @return list 返回list集合,集合中存放的是map,map中以键值对的方式存放取出来的值。
     */
    public static List<Map> getList(String env, String sql, String... columnLabel) {

        Connection connection = getConnection(env);
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        String result = "";
        HashMap map = null;
        List<Map> list = new ArrayList();

        try {
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                for (String column:columnLabel) {
                    map = new HashMap();
                    result = resultSet.getString(column);
                    map.put(column,result);
                    list.add(map);
                }
            }
            connection.close();
            resultSet.close();
            statement.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(CollectionUtils.isEmpty(list)) {
            return null;
        } else {
            return list;
        }
    }

}

相关文章

网友评论

      本文标题:封装从配置文件中读取数据连接数据库取数据

      本文链接:https://www.haomeiwen.com/subject/jqrirctx.html