我正在制作一个程序,它使用Java作为前端来对数据进行一些SQL操作。我已经完成了大部分设置,并且我能够连接到我的数据库,但是出于某种原因,当我尝试运行我的查询时,它会返回一行说“"无法执行查询&# 34;我无法弄清楚为什么它不能执行查询。
public class application {
public static void main (String args[]) throws Exception,
IOException, SQLException {
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println ("Could not load the driver");
}
String user = readEntry("Enter userid: ");
String pass = readEntry("Enter password: ");
Connection conn = DriverManager.getConnection (
"jdbc:oracle:thin:@serveraddress",user,pass);
boolean done = false;
do {
printMenu();
System.out.print("Type in your option: ");
System.out.flush();
String ch = readLine();
System.out.println();
switch (ch.charAt(0)) {
case '1': studentModules(conn);
break;
//some other cases
case '0': done = true;
break;
default : System.out.println(" Not a valid option ");
} //switch
} while(!done);
} // main
private static void studentModules(Connection conn) throws SQLException, IOException {
String sqlString = null;
Statement stmt = conn.createStatement();
sqlString = "select Student_id" +
"from STUDENT;";
ResultSet rset;
ResultSet rset2;
try {
rset = stmt.executeQuery(sqlString);
} catch (SQLException e) {
System.out.println("Could not execute query");
stmt.close();
return;
}
String print;
while (rset.next()) {
print = rset.getString(1) + ": ";
sqlString = "select Module_code" +
"from EXAM" +
"where Student_id = " + rset.getString(1) + ";";
try {
rset2 = stmt.executeQuery(sqlString);
} catch (SQLException e) {
System.out.println("Could not execute query");
stmt.close();
return;
}
while (rset2.next()) {
print = print + rset.getString(1) + " ";
}
System.out.println(print);
}
stmt.close();
}
我知道这是一段很长的代码,但我无法理解为什么会出错。我知道这是错误的,并且在尝试查询&#34; SELECT Student_id FROM STUDENT&#34;时被抓住了,但该查询没有错,我无法理解为什么会在那里引发错误?< / p>
感谢您的帮助。
答案 0 :(得分:1)
"select Student_id" +
"from STUDENT;";
解析为select Student_idfrom STUDENT
之类的无法计算的内容。做
"select Student_id from STUDENT";
代替。
sqlString = "select Module_code" +
"from EXAM" +
"where Student_id = " + rset.getString(1) + ";";
应该是
sqlString = "select Module_code from EXAM " +
" where Student_id = " + rset.getString(1);
同样。
不要对最终的';'进行编码顺便说一下 - 有些数据库(比如ORACLE)讨厌很多。
哦,你的最终结果集中的循环变量你需要访问rset2而不是rset,我猜:
while (rset2.next()) {
print = print + rset2.getString(1) + " "; //CHECK
}
其他强>
您可能还想考虑使用PreparedStatement
- 字符串连接将打开SQL注入的大门,您可能希望阻止它。
答案 1 :(得分:1)
您的查询无效:
sqlString = "select Student_id" +
"from STUDENT;";
评估为“从学生中选择Student_id”,因此您缺少空白。
同样适用于
sqlString = "select Module_code" +
"from EXAM" +
"where Student_id = " + rset.getString(1) + ";";
您在“Module_code”和“from”以及“EXAM”和“where”之间缺少空白。
您应该执行类似
的操作 sqlString = "select Student_id " +
"from STUDENT;";
和
sqlString = "select Module_code " +
"from EXAM " +
"where Student_id = " + rset.getString(1) + ";";
答案 2 :(得分:0)
"select Student_id" + "from STUDENT;";
不会在两个字符串之间添加任何空格,但你肯定需要它