mysql - 每当我提交表单时都会出现 sql 错误

标签 mysql sql servlets

我正在尝试从 mySQL 数据库获取数据并将其存储到我的 arrayList 中。但是,每当我运行这组代码时,我都会收到此错误

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 'displayname LIKE '%A%'' at line 1

但是,我没有使用任何关键字,我为通配符运算符添加了单引号。我的sql语句哪里做错或者遗漏了?

String sql = "SELECT * FROM azq.registration WHERE userId NOT IN (SELECT friendId FROM azq.friendlist WHERE userId ="
                        + session.getAttribute("userId")
                        + ") AND userId !="
                        + session.getAttribute("userId")
                        + "AND displayname LIKE '%" + searchText + "%'";
                // create the java statement
                Statement st = conn.createStatement();

                // execute the query, and get a java resultset
                ResultSet rs = st.executeQuery(sql);

                // iterate through the java resultset
                while (rs.next()) {
                    Friends newList = new Friends();
                    newList.setFirstName(rs.getString("firstName"));
                    newList.setLastName(rs.getString("lastName"));
                    newList.setUserId(rs.getString("userId"));
                    newList.setDisplayname(rs.getString("displayname"));

                    resultList.add(newList);
                }
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }

最佳答案

您必须在AND之前添加一个空格:

                + session.getAttribute("userId")
                    + " AND displayname LIKE '%" + searchText + "%'";

关于mysql - 每当我提交表单时都会出现 sql 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38484620/

相关文章:

MySQL - 将列乘以别名

mysql - 在左连接上按 desc 排序很慢

php - SQL 外键用法?它到底有什么作用?什么时候需要?

java - 在测试和开发期间快速启动 JAX-RS 应用程序

java - 简单 HTTP 请求与 Web 服务

java - 使用DriverManager类设置jdbc拦截器

php - 商店的表格结构 - 商品 - 价格

mysql - 从两个表中检索数据时如何填充文本框?

java - Hibernate IN关键字在where子句之前有什么用

jakarta-ee - 基于表单的身份验证,但在 Java EE 6 中使用自定义身份验证方法