我有两个名为mytest和class的表,我需要做的是通过两个表中都存在的列ID将它们连接起来,但是问题是我需要对firstName列进行参数化才能连接所选的firstName,而不是与fristName列具有相同ID的所有列,这是我得到的要点,但是我有一个错误
SELECT mytest.firstName,class.name
FROM mytest
INNER JOIN class ON mytest.id=class.id
where fristName=?
错误
> Servlet.service() for servlet [com.web.studentregister] in context with path [/MySystemApp] threw exception [com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?' at line 1] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?' at line 1
我还必须提到我正在servlet应用程序中使用此查询,这也是与此查询交互的代码
数据库类
public List <studentrgister> showcourse(String names) throws Exception {
List<studentrgister> students = new ArrayList<>();
String connectionURL = "jdbc:mysql://localhost:3306/web_student_tracker";
System.out.println("loding the driver");
Statement s=null;
studentrgister mystudent=null;
Connection myConn = null;
myConn= DriverManager.getConnection(connectionURL, "webstudent", "webstudent");
System.out.println("username and password is correect");
PreparedStatement myStmt=null;
ResultSet myRs = null;
String name=names;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver is loaded");
String sql="SELECT mytest.firstName,class.name FROM mytest INNER JOIN class ON mytest.id=class.id where mytest.firstName=? " ;
s =myConn.createStatement();
s.executeQuery(sql);
myRs=s.getResultSet();
if (myRs.next()) {
String classname = myRs.getString("name");
int numbername=myRs.getInt("firstName");
mystudent = new studentrgister(classname,numbername);
students.add(mystudent);
}
else {
throw new Exception("Could not find student id: " );
}
return students;
}
finally {
close(myConn,myStmt,null);
}
}
servlet类
private void seecourse(HttpServletRequest request, HttpServletResponse response) throws Exception {
String names=request.getParameter("names");
student_db_util.showcourse(names);
List<studentrgister> student=student_db_util.showcourse(names);
request.setAttribute("mycourse", student);
RequestDispatcher rd=request.getRequestDispatcher("showcourse.jsp");
rd.forward(request,response);
}
我发送firstName参数的jsp页面
<form action="studentregister" method="get">
<input type="hidden" name="command" value="pass" />
<table>
<c:forEach var="tempstudent" items="${studentlist}">
<c:url var="seecourse" value="studentregister">
<c:param name="command" value="seecourse"/>
<c:param name="names" value="${tempstudent.name}"/>
</c:url>
<td >${tempstudent.email}</td>
<td >${tempstudent.name}</td>
<a href="${seecourse}"
>
seecourse</a>
</c:forEach>
</table>
</form>
如果要在SQL语句中使用参数,则需要使用PreparedStatement
。例如: