如何使用JSP从数据库中获取元组

时间:2016-07-17 05:45:44

标签: mysql jsp

我需要按照用户在上一页中指定的方式进行检索所以我在这里写了代码但是我得到了

无法连接到databasejava.sql.SQLException:您的SQL语法中有错误;请查看与您的MYSQL服务器版本对应的手册,以便在' == t)'附近使用正确的语法。

我的代码

   <%@ page import="java.sql.*" %> 
   <%@ page import="java.io.*" %> 
   <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  pageEncoding="ISO-8859-1"%>
   <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
   <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
   <html>
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
   <title>Insert title here</title>
   </head>
   <body>
   <%
    try 
     {
      String t=request.getParameter("val");
      String connectionURL = "jdbc:mysql://localhost/tables";
      Connection connection = null; 
      Class.forName("com.mysql.jdbc.Driver"); 
      connection = DriverManager.getConnection(connectionURL, "root", "");
      Statement st = connection.createStatement();
            String query="select * from details where sno==t)";
            ResultSet rs = st.executeQuery(query);
            if(!connection.isClosed())
            {
                while(rs.next())
                {       
                 out.println(rs.getString(1)); 
                 out.println(rs.getString(2)); 
                 out.println(rs.getString(3)); 
                 out.println("<br>");
                }
             }
         } 
             connection.close();
       }
       catch(Exception ex)
      {
         out.println("Unable to connect to database"+ex);
       }        
     }
   }
   %>
   </body>
    </html>

1 个答案:

答案 0 :(得分:0)

MySQL中的比较运算符是=而不是==

代码段

int param = Integer.parseInt(t);
String query="select * from details where sno = "+param;
System.out.println("query="+query);    
ResultSet rs = st.executeQuery(query);

实际上,您应该像下面这样指定以符合数据类型:

out.println(rs.getInt("sno")); 
out.println(rs.getInt("Id")); 
out.println(rs.getString("name"));
out.println(rs.getInt("mobile"));