Return string in SQLITE query

Asked

Viewed 631 times

0

I need to return a user’s name in an SQLITE query: I’m using the following code:

public String verificarUsuario(String login)
    {

        try
        {

        String selectQuery = "select nome from usuarios where login = " + login;

        Cursor cursor = db.rawQuery(selectQuery, null);
        cursor.moveToFirst();

        String nomeString = cursor.getString(cursor.getColumnIndex("tipoFunc"));

        StringBuilder conversor = new StringBuilder();
        conversor.append(nomeString);
        return conversor.toString();


        }

But the following error is appearing:

no such column: lgomes (code 1): , while compiling: select name from usuarios Where login=lgomes

1 answer

3


The user name must be in quotes to represent a string.

If you do not use quotes the database will try to compare the column login with another column. See the error message:

in such column: lgomes

In free translation

No column called lgomes

Your code should be something like:

String selectQuery = "select nome from usuarios where login = '" + login + "'";

The second mistake is why you have to use the index column:

String nomeString = cursor.getString(cursor.getColumnIndex("nome"))

It would be good to note that riding darlings concatenating strings can make your application susceptible to SQL injection attacks. Be careful with this.

Read these questions if you want to learn more.

  • Thanks!! It worked, now it worked java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.

  • @Lucascharles this error is because you have to put the correct index: String nomeString = cursor.getString(cursor.getColumnIndex("nome"))

  • Well, there’s another problem, @Lucascharles I think you should open a new question, with this information and the stacktrace of error.

  • @Lucascharles cursor.getColumnIndex("name")

  • 1

    @acklay Thank you so much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.