如何连接jdbc中不同表中的记录
我想在JDBC的不同表中联接并显示列,但它出现了一些错误,谁能帮我。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。 非常感谢 这就是错误:如何连接jdbc中不同表中的记录,jdbc,Jdbc,我想在JDBC的不同表中联接并显示列,但它出现了一些错误,谁能帮我。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。 非常感谢 这就是错误: private void CoursesOfStudent () throws SQLException, IOException { try { String sql = "SELECT Students.StudentId, Studen
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();
}
}
听起来您的MySQL/MySQL JDBC驱动程序无法处理准备好的语句 问:您使用的是MySQL 5.0还是更高版本 此外: 确保所有SQL语句之间都有空格。不要依赖“\n”: 例如:
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
我认为你应该试着使用;之后也Rest取决于您使用的驱动程序版本。您使用了错误的
执行方法。在使用PreparedStatement
时,在执行先前准备的语句时,应使用不带字符串参数的executeQuery()
因此,请使用:
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 = ?";
如果使用以下命令,JDBC api甚至需要准备好的语句来抛出SQLException
:
抛出:
SQLException
-,在PreparedStatement
或CallableStatement
ResultSet rs = stmt.executeQuery();