jdbc 实现ActiveRecord

DBUtils.java

public class DBUtils {
    private static String driverClassName;
    private static String url;
    private static String username;
    private static String password;


    public List find(String sql) {
        List records = new ArrayList<>();
        Statement statement;
        try {
            statement = getConnection().createStatement();
            ResultSet resultSet = statement.executeQuery(sql);
            //获取元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            //获取共有多少字段
            int columnCount = metaData.getColumnCount();
            while (resultSet.next()) {
                Record record = new Record();
                for (int i = 0; i < columnCount; i++) {
                    //获取字段名
                    String columnName = metaData.getColumnLabel(i);
                    //通过字段名获取数据
                    record.put(columnName, resultSet.getObject(columnName));
                }
                records.add(record);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return records;
    }

    public static Connection getConnection() {
        try {
            Class.forName(driverClassName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}

Record.java

import java.util.HashMap;

public class Record extends HashMap {

    public Integer getInt(String col) {
        return Integer.parseInt((String) this.get(col));
    }

}

你可能感兴趣的:(杂记)