猿问

如何摆脱第二个参数?

我创建了一个方法 ( getData()) 来从数据库接收数据,这似乎有效。我想要的是只使用 1 个参数,所以该方法应该以className.getData("SELECT * FROM myTable"). 我怎样才能做到这一点?


public List<String> getData(String sql, Map column) {

    this.driver();

    try {

        Connection conn = DriverManager.getConnection(this.url);

        Statement stmt = conn.createStatement();

        ResultSet rs = stmt.executeQuery(sql);


        List<String> result = new ArrayList<>();

        if (column.containsKey("string")) {

            for (Object i : column.values()) {

                while (rs.next()) {

                    result.add(rs.getString(String.valueOf(i)));

                }

            }

            return result;

        }


    }

    catch (SQLException e) {

        e.printStackTrace();

    }

    return null;

}


private void driver() {

    // Ensure we have mariadb Driver in classpath

    try {

        Class.forName("org.mariadb.jdbc.Driver");

    }

    catch (ClassNotFoundException e) {

        e.printStackTrace();

    }

}


犯罪嫌疑人X
浏览 111回答 2
2回答

慕妹3146593

当然,您不需要将列名作为参数传递。JDBC 允许您从元数据中获取列名。就像下面一样ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");ResultSetMetaData rsmd = rs.getMetaData();Integer colunNum = rsmd.getColumnCount();for(int i =0; i < columnNum; i ++){&nbsp; &nbsp; String colmnName = rsmd.getColumnName(i);&nbsp; &nbsp; ....}归功于:从 java.sql.ResultSet 中检索列名

婷婷同学_

在类实例化中调用驱动方法。static {&nbsp; &nbsp; // Ensure we have mariadb Driver in classpath&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; Class.forName("org.mariadb.jdbc.Driver");&nbsp; &nbsp; }&nbsp; &nbsp; catch (ClassNotFoundException e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }}你也应该关闭你的资源。您可以使用try-with-resources来做到这一点。public List<String> getData(String sql, Map column) {&nbsp; &nbsp; try (&nbsp; &nbsp; &nbsp; &nbsp; Connection conn = DriverManager.getConnection(this.url);&nbsp; &nbsp; &nbsp; &nbsp; Statement stmt = conn.createStatement();&nbsp; &nbsp; &nbsp; &nbsp; ResultSet rs = stmt.executeQuery(sql);&nbsp; &nbsp; &nbsp;){&nbsp; &nbsp; &nbsp; &nbsp; List<String> result = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; if (column.containsKey("string")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (Object i : column.values()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while (rs.next()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.add(rs.getString(String.valueOf(i)));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return result;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; catch (SQLException e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }&nbsp; &nbsp; return null;}
随时随地看视频慕课网APP

相关分类

Java
我要回答