简体   繁体   English

JDBC + Java查询执行错误

[英]JDBC + Java Query execution error

I'm getting this exception 我收到这个例外

java.sql.SQLException: Unknown column 'auyu' in 'where clause'

My Query and method in my database facade class. 我的数据库外观类中的查询和方法。

db.save("delete from users where name = auyu");

public static void save(String sql) throws Exception {
        new DBFacade().connect();
        synchronized (c) {
            c.createStatement().executeUpdate(sql);
        }
}

I suspect you meant: 我怀疑你的意思是:

delete from users where name = 'auyu'

This is still a pretty odd SQL command to give to a "save" method. 赋予“保存”方法仍然是一个很奇怪的SQL命令。

I'd also strongly suggest that you use parameterised SQL statements instead of embedding data directly into the SQL itself - particularly if the data has come from the user. 我也强烈建议您使用参数化的SQL语句,而不是直接将数据嵌入到SQL本身中-特别是如果数据来自用户。

您需要在auya('auyu')周围加上单引号,并且需要像这样转义它们:

"delete from users where name = \'auyu\'"

+1 to Jon Skeet's answer. +1为乔恩·斯基特(Jon Skeet)的答案。 Expanding and perhaps going OT, but it's best to parameterize these things and ensure escaping so that you aren't susceptible to SQL-injection attacks. 扩展并可能进行OT,但是最好将这些内容参数化并确保转义,以免受到SQL注入攻击的影响。 Eg: 例如:

public static void deleteUser(userName)
throws Exception
{
    PreparedStatement ps;

    new DBFacade().connect();
    // (Assuming 'c' is a connection that's in scope somehow)
    synchronized (c) {
        // (You'd want to cache the prepared statement in an appropriate
        // way related to how you're handling connections and pooling)
        ps = c.prepareStatement("delete from users where name = ?");
        ps.setString(1, userName);
        ps.executeUpdate();
    }
}

Otherwise, if a user provides a name like "anyu'; drop table users;", you could be for it. 否则,如果用户提供的名称类似于“ anyu'; drop table users;”,则可能适合您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM