private void CoursesOfStudent () throws SQLException, IOException {
try {
String sql = "SELECT Students.StudentId, Students.Name, Courses.Name,Grade\n"
+ " FROM Students LEFT JOIN StudentCourses\n"
+ "ON Students.StudentId = StudentCourses.StudentId\n"
+ "LEFT JOIN Courses ON Courses.CourseId = StudentCourses.CourseId\n"
+ "WHERE Students.StudentId = ?";
pre = connection.prepareStatement(sql);
System.out.print("Let put Id of student that you wanna list all of courses: ");
int Stid = Integer.parseInt(reader.readLine());
pre.setInt(1, Stid);
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Stid = rs.getInt("StudentId");
String Stname = rs.getString("Students.Name");
String Coname = rs.getString("Courses.Name");
int grade = rs.getInt("Grade");
System.out.print("StudentId: " + Stid);
System.out.print(", StudentName: " + Stname);
System.out.print(", CourseName: " + Coname);
System.out.println(", Grade: " + grade);
}
pre.executeUpdate();
}catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
我想加入并在JDBC中的不同表中显示列,但它有一些错误,谁可以帮助我........................ ........................................... 非常感谢!
这是错误:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 5
答案 0 :(得分:0)
听起来你的MySQL / MySQL JDBC驱动程序无法处理准备好的语句。
问:您使用的是MySQL 5.0或更高版本吗?
ALSO:
确保所有SQL语句之间都有空格。不要依赖“\ n”:
实施例
String sql = "SELECT Students.StudentId, Students.Name, Courses.Name,Grade\n"
+ " FROM Students LEFT JOIN StudentCourses\n"
+ " ON Students.StudentId = StudentCourses.StudentId\n"
+ " LEFT JOIN Courses ON Courses.CourseId = StudentCourses.CourseId\n"
+ " WHERE Students.StudentId = ?";
答案 1 :(得分:0)
我认为你应该尝试使用;之后?同样。休息取决于您使用的驱动程序版本。
答案 2 :(得分:0)
您使用了错误的executeQuery
方法。当您使用PreparedStatement
时,在执行先前准备的语句时,应使用不带字符串参数的executeQuery()
。
所以使用:
ResultSet rs = stmt.executeQuery();
如果你使用executeQuery
that takes a string,JDBC api甚至需要准备好的语句抛出SQLException
:
<强>抛出:强>
上调用
SQLException
- ...,该方法在PreparedStatement
或CallableStatement