【问题标题】:MySQL SyntaxErrorExceptionMySQL 语法错误异常
【发布时间】:2017-11-19 13:04:29
【问题描述】:

public static LoginBean logIn(String userName)throw Exception{

    String query="select user_name, password from login where user_name="+userName;
    System.out.println(query);

    Statement st=null;
    ResultSet result=null;
    LoginBean bean=new LoginBean();
    try{
        st=con.createStatement();
        result=st.executeQuery(query);

        while(result.next()){

            bean.setUserName(result.getString("user_name"));
            bean.setPassword(result.getString("password"));
        }
        return bean;
    }
    finally
    {
        if(result!=null)
        {
            result.close();
        }
        if(st!=null)
        {
            st.close();
        }            
    }
}

我正在执行此方法,但它给了我错误,即com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'admin' in 'where clause' 我检查了语法但找不到错误。

【问题讨论】:

  • “我已经检查了语法” - 你有吗?您能否在问题中包含您尝试执行的 SQL 查询的实际运行时值?告诉我们您已经检查过它并且您认为它是正确的与向我们展示它以便我们可以检查它是不同的。

标签: java mysql


【解决方案1】:

您在用户名“admin”周围缺少引号,这使mySQL 认为您指的是列名而不是值。

也就是说,你应该使用PreparedStatement

String query="select user_name, password from login where user_name=?";
System.out.println(query);

PreparedStatement st=null;
ResultSet result=null;
LoginBean bean=new LoginBean();
try{
    st=con.prepareStatement(query);
    st.setString(1,userName);
    result=st.executeQuery();
    ...

【讨论】:

  • 我希望我们可以根除所有不使用PreparedStatement 的教程和代码sn-p。
  • setString(1, userName)的方法是什么;为??
  • @TaimoorKhan 将 SQL 字符串中的? 替换为userName 变量中存储的值。
猜你喜欢
  • 2013-06-04
  • 1970-01-01
  • 2015-12-29
  • 2015-12-12
  • 2017-09-01
  • 2011-01-11
  • 2013-02-24
  • 1970-01-01
相关资源
最近更新 更多