任何人都可以请更正此SQL语法异常

时间:2015-06-16 01:43:29

标签: java mysql

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{   
    String index= request.getParameter("Index");
    index=index.trim();

    System.out.println(index);

    PrintWriter out = response.getWriter();
    try 
    {
        Class.forName("com.mysql.jdbc.Driver");
        Connection dbConnection=DriverManager.getConnection("jdbc:mysql://localhost:3306/smb","root","");
        System.out.println(" Connected ");

        PreparedStatement ps=(PreparedStatement) dbConnection.prepareStatement(" select index from books where index=? ");
        System.out.println(" Prepared ");

        try
        {           
            ps.setString(1, index);         
            ResultSet rs = ps.executeQuery();               

            String keysInDb;
            keysInDb="";

            while(rs.next())
            {
                keysInDb=rs.getString(1);
                System.out.println(keysInDb);
            }

            dbConnection.close();

        }
        catch (Exception e) 
        {
            System.out.println("ERROR : "+e);
        }



    }
    catch (Exception e) 
    {
        out.print(e);
    }



}
  

错误:com.mysql.jdbc.exceptions.MySQLSyntaxErrorException:SQL语法中有错误;检查与MySQL服务器版本对应的手册,以便在第1行的'index ='2''附近使用正确的语法

1 个答案:

答案 0 :(得分:0)

index是一个关键字,如果您将其用作列名,请尝试使用倾斜来转义它。 (`)

....
PreparedStatement ps=(PreparedStatement) dbConnection.prepareStatement(" select `index` from books where `index`=? ");
....