【问题标题】:MySQL Query Error SQLExceptionMySQL 查询错误 SQLException
【发布时间】:2014-03-06 10:04:32
【问题描述】:

我在尝试将查询请求实现到程序中时遇到了这个问题。不使用此方法连接到数据库可以正常工作,但是,这会引发 SQLException

    String query = "SELECT EXISTS ( SELECT * FROM usr WHERE username = admin AND password = pass )";
    boolean result;
    Connection con = null;
    try {
        con = DriverManager.getConnection(url, username, password);
        Statement stmt = (Statement) con.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        result = rs.next();
    } catch (SQLException e) {
        throw new RuntimeException("Cannot connect to the database!", e);
    } finally {
        System.out.println("Closing the connection.");
        if (con != null)
            try {
                con.close();
            } catch (SQLException ignore) {
                System.out.println("Unknown Error Connecting to MySQL Server!");
            }
    }

我将查询引入到隔离它的方法中。 任何帮助将不胜感激。

【问题讨论】:

  • 研究使用准备好的语句:Link:它们几乎消除了处理引用字符串/varchar 字段的麻烦。在您的情况下,adminpass 没有正确地用单引号括起来。

标签: java jquery mysql sqlexception


【解决方案1】:

通常搜索字符串 - 您需要将值单引号 - 因此在 where 子句中替换为 'admin''pass'

【讨论】:

  • 啊,这解决了它,但是,现在它总是返回 true,即使值不正确。有什么想法吗?
  • 不,应该可以。我在我的一个 MySQL 数据库上尝试了一个非常相似的查询并且它有效。现在,结果是 1(存在)或 0(不存在)。您可能想尝试直接对数据库运行查询 - 使用 mysql 命令行。
猜你喜欢
  • 2011-11-13
  • 1970-01-01
  • 1970-01-01
  • 2016-03-29
  • 2012-05-27
  • 1970-01-01
  • 1970-01-01
  • 2012-10-11
  • 2011-08-18
相关资源
最近更新 更多