2017-01-30 5 views
1

これは私のコードの小さな部分です。基本的に、私は私の結果セットを印刷するか、それを文字列に変換する方法を知らない。文字列に変換してResultSetを出力する方法がわからない、SELECT文

try { 
    String url = "jdbc:odbc:" + "userstuff"; 
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
    Connection con = DriverManager.getConnection(url,"",""); 
    // Gets a statement 
    Statement state = con.createStatement(); 
    String query = "SELECT description FROM topics WHERE title = '" + title + "'"; 
    String query2 = "SELECT * FROM comment WHERE topic = '" + title + "'"; 
    // selects the description for the selected topic (title will be referenced to the chosen topic) 
    ResultSet results = state.executeQuery(query); 
    // selects * of the rows from "comment" table where the topic equals the selected title. 
    ResultSet results2 = state.executeQuery(query2); 
    desc = results.toString(); 
} 
+0

これは良いコードではありません。簡単な答えは、すべてのResultSetをオブジェクトまたはデータ構造にマップし、スコープ内で閉じることです。 PreparedStatementの使い方を学んでください。必要に応じて手動でクエリ文字列を作成しないでください。 "SQLインジェクション"の理由を理解するGoogle。 ODBCブリッジドライバは、JDK 8では使用できなくなりました。依存しないでください。 – duffymo

+0

大丈夫、ヒントや助けを感謝します。私は自分のコードを改良しようとしますが、これは全く新しいものです。 – Questioning

答えて

1

結果セットをResultSetから直接印刷することも、文字列に変換することもできません。

次のコードを参考にしてください。

try { 
    String url = "jdbc:odbc:" + "userstuff"; 

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 

    Connection con = DriverManager.getConnection(url,"",""); 

    // Gets a statement 
    Statement state1 = con.createStatement(); 
    Statement state2 = con.createStatement(); 

    String query1 = "SELECT description FROM topics WHERE title = '" + title + "'"; 

    // selects the description for the selected topic (title will be referenced to the chosen topic) 
    ResultSet results1 = state1.executeQuery(query1); 

    while(results.next()){ 

     System.out.println(results1.getString("description"); 
    } 

    // selects * of the rows from "comment" table where the topic equals the selected title. 
    String query2 = "SELECT * FROM comment WHERE topic = '" + title + "'"; 

    ResultSet results2 = state2.executeQuery(query2); 

    while(results2.next()){ 

     System.out.println(results2.getString(1); // here 1 is tables 1st column 
     System.out.println(results2.getString(2); // here 2 is tables 2nd column 
    } 
} Exception(SQL e){ 

    e.printStackTrace(); 
} 
+0

ああ大丈夫です!あなたの助けをありがとう、それははるかに良い作品のように見えます。 – Questioning

関連する問題