2016-11-18 82 views
0

我正在爲一個類的項目工作,並且是使用JDBC的初學者。對於一部分,我的導師希望我們「提供一個查詢菜單,允許用戶輸入查詢命令並從數據庫中檢索信息。」我已經研究了很多,並且無法找到辦法做到這一點。我見過的大多數例子已經知道用戶將要查詢什麼。如果我允許用​​戶查詢任何內容,如何返回正確的信息?我到目前爲止的代碼如下。基於用戶輸入使用JDBC從SQL數據庫檢索數據?

System.out.println("What table do you wish to query?"); 
table = scan.nextLine(); 
System.out.println("What values do you wish to query? Type them separated by commas. If you wish to select all values, please type a *."); 
values = scan.nextLine(); 
System.out.println("Type the conditions for your WHERE clause, excluding the keyword WHERE."); 
conditions = scan.nextLine(); 
query = "SELECT " + values + " FROM " + table + "WHERE " + conditions; 
try { 
    stmt = con.createStatement(); 
    ResultSet rs = stmt.executeQuery(query); 
    while (rs.next()) { 
     if(values != "*") 
      String results = rs.getString(values); 
    } 

還有就是我堅持,因爲我不知道用戶要查詢,所以我不知道要放什麼東西在while循環,在這個例子中,他們知道用戶正在尋找姓氏。

rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = 2001"); 
while (rs.next()) { 
    String lastName = rs.getString("Lname"); 
    System.out.println(lastName); 
} 

任何幫助或建議將不勝感激。

+0

剛剛在這裏得到了一個ping。重複的標註是否已發佈和刪除? – Drew

+1

@德魯是啊我認爲更具體的答案張貼如此.. –

回答

0

我認爲你有基礎知識,所以我會給你pseduocode的一種可能的方式來做到這一點,讓你填寫空白。

1) input user values and put in an array (VALUESARRAY) 
2) validate values against table field names (exit if invalid) 
3) prepare query 
4) execute query 
5) loop through the VALUEARRAY and get appropriate value from the result set  
    (same as you did in your example). 

我覺得#5是你不知道該怎麼做,但使用數組應該可以解決這個問題。

相關問題