5

I'm writing a Java app which has to add a record to a database. Everything works fine until I want to add a local variable to the database (I think I'm placing my parentheses wrong or something). Anyway, I'm tired of looking for the problem and would appreciate some help.

My code:

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) {
    }
}

The error:

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)

Thanks, Tom

3
  • 6
    WARNING your code is susceptible to sql injection attacks. Commented Feb 18, 2012 at 22:41
  • 1
    @Thomas you have to put username as 'Robert'); DROP TABLE Users; --' as ' is missing in the query...;) Commented Feb 19, 2012 at 3:44
  • 3
    Oh, yes. Little Bobby Single Quotes, they call me. Commented Feb 19, 2012 at 14:09

2 Answers 2

19

The problem is the in query. The userName variable is not enclosed in quotes

Use below code:

statement.execute("insert into Users values(" + 1 + ",'"  +  userName  + "',"  + "'Helloskit'" +") ");
Sign up to request clarification or add additional context in comments.

2 Comments

@Lion why? It looks like a string literal to me.
I know of someone who's family name is “O'Sullivan”. Single quotes happen in real data. Use prepared statements.
1

In your SQL statement, the variable userName should be in quotes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.