0

既に作成されて入力されているテーブル内のすべての行を取得しようとしています。これは私が現在やろうとしている機能ですが、明らかに機能しません。何も出さない。

    public static void getTable(String[] table) throws ClassNotFoundException, SQLException{
    DatabaseMetaData metadata = null;
    Class.forName(driver);
    conn = DriverManager.getConnection(connectionURL);  

    metadata = conn.getMetaData();
    ResultSet res = metadata.getTables(null, null, null, table);

    while(res.next()){
        System.out.println(res.toString());
    }
    res.close();
    conn.close();
}

私が間違っていることはありますか?


ふぅ、組み合わせで数時間遊んだ後。私は何かを持っています。それは私にすべてを苛立たせますが、この種の問題を抱えている可能性のある人のために、テーブル全体からデータを取得するために私が思いついたものを次に示します。

編集: 行番号と値が「,」で区切られた HashMap を返すようになりました。

    /**
 * Gets all rows of a table. Returns a HashMap.
 * 
 * Returns a HashMap with each table row value separated by ','. 
 * Each row in a new count in the hashmap. Example:
 * 
 * Returns:
 * 
 * <1, "FirstName,LastName,Age">
 * 
 * 
 * @param table
 * @return HashMap<Int, String>
 * @throws ClassNotFoundException
 * @throws SQLException
 */
@SuppressWarnings("null")
public static HashMap<Integer, String> getTable(String table) throws ClassNotFoundException, SQLException{
    DatabaseMetaData metadata = null;
    Class.forName(driver);
    conn = DriverManager.getConnection(connectionURL);  

    String sql = "select * from " + table;  // use actual name of the table
    PreparedStatement statement = conn.prepareStatement(sql);
    ResultSet res = statement.executeQuery();
    ResultSetMetaData md = res.getMetaData();
    HashMap<Integer,String> hash = new HashMap();
    int count = md.getColumnCount();
    String done;
    int y = 1;
    while(res.next()){
        for(int x = 1; x < md.getColumnCount(); x = x+md.getColumnCount()){
            done = res.getObject(x).toString() + "," + res.getObject(x+1).toString();
        }
        hash.put(y, done);
        y++;
    }
    res.close();
    conn.close();
    if(!hash.isEmpty())
        return hash;
    else
        return null;
}
4

1 に答える 1

2

次のようなSQLステートメントを使用して実行できます。

String sql = "select * from <nameOfTable>";  // use actual name of the table
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet rs = statement.execute();

これはあなたが求めていることを行います。

今、あなたが次に何をするかを知っているかどうかは明らかではありません。列の名前を知らないようにしようとしていると言うので、実際にはメタデータにクエリを実行してそれらの名前を取得する必要があります。列の位置によって結果セットからデータを取得できますが、列のデータ型 (string、int、blob) を知ることはできません。

メタデータから取得した列を反復処理して名前と (おそらくもっと重要な) データ型を見つけ、取得する各列の結果セットで getInt または getString を呼び出すことができます。

したがって、これが実際の質問に対する答えかもしれませんが、それを使って何か役に立つことを行うには、さらに多くのロジックが必要になります。私たちはそれを手伝うことができますが、今はあなたがそうしたいと思っているだけだと思います...

于 2012-06-17T03:05:32.640 に答える