2016-11-18 81 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是你不知道该怎么做,但使用数组应该可以解决这个问题。

相关问题