2017-01-30 21 views
1

这是我的一小段代码。基本上,我不知道如何打印我的ResultSet或将它变成字符串。不知道如何转换为字符串并打印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注入”来理解为什么。 ODBC桥驱动程序在JDK 8中不再可用。您不应该依赖它。 – duffymo

+0

好的,谢谢你的提示和帮助。我会尽力改进我的代码,对此我很陌生。 – Questioning

回答

1

您不能将ResultSet转换为字符串,也不能直接从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

相关问题