【问题标题】:Java SQLite : no such column errorJava SQLite:没有这样的列错误
【发布时间】:2012-02-18 22:40:10
【问题描述】:

我正在编写一个必须将记录添加到数据库的 Java 应用程序。一切正常,直到我想向数据库添加一个局部变量(我想我把括号放错了)。无论如何,我已经厌倦了寻找问题并希望得到一些帮助。

我的代码:

public void newUser(int userID, String userName, String credentials) {
    try {
        Class.forName("org.sqlite.JDBC");
        conn = DriverManager
                .getConnection("jdbc:sqlite:c:/temp/alarmsystem.db");
        Statement statement = conn.createStatement();
        statement.execute("insert into Users values(" + 1 + "," + userName
                + "," + "'Helloskit'" + ") ");
        core.printToConsole("created");
        ResultSet rs = statement.executeQuery("select * from Users");

        while (rs.next()) {
            String s = rs.getString("Username");

            core.printToConsole("name = " + s);

        }
    } catch (Exception e) {
    }
}

错误:

java.sql.SQLException: no such column: Tombellens
at org.sqlite.DB.throwex(DB.java:288)
at org.sqlite.NestedDB.prepare(NestedDB.java:115)
at org.sqlite.DB.prepare(DB.java:114)
at org.sqlite.Stmt.execute(Stmt.java:82)
at me.server.DBCommunications.DBConnection.newUser(DBConnection.java:59)
at me.server.Core.Core.newUser(Core.java:61)
at me.server.LocalUser.Console.main(Console.java:72)

谢谢,汤姆

【问题讨论】:

  • 警告您的代码容易受到 sql 注入攻击。
  • @Thomas 您必须将用户名输入为'Robert'); DROP TABLE Users; --',因为查询中缺少 '...;)
  • 哦,是的。小鲍比单引号,他们叫我。

标签: java sql sqlite


【解决方案1】:

问题在于 in 查询。 userName 变量没有用引号括起来

使用下面的代码:

statement.execute("insert into Users values(" + 1 + ",'"  +  userName  + "',"  + "'Helloskit'" +") ");

【讨论】:

  • @Lion 为什么?对我来说,它看起来像一个字符串文字。
  • 我知道有人姓“O'Sullivan”。 单引号出现在真实数据中。使用准备好的语句。
【解决方案2】:

在您的 SQL 语句中,变量 userName 应该用引号引起来。

【讨论】:

    猜你喜欢
    • 2017-02-09
    • 2015-09-07
    • 1970-01-01
    • 2022-01-19
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    相关资源
    最近更新 更多