Stranger B.
Stranger B.

Reputation: 9364

How to avoid special characters SQLite Android

I'm facing an issue with SQLite in Android, I know the solution must be simple, but what I have done is not working !!

 // Update a contact with a new name
    public void updatename (String phone, String newname) {
        newname = newname.replaceAll("'","\'");
        String query = "UPDATE contacts SET name = '"+newname+"' WHERE phone = '"+phone+"'";
        SQLiteDatabase db = this.getWritableDatabase();

        db.execSQL(query);

        //db.close();


    }

the replace function is not working !!

Upvotes: 0

Views: 166

Answers (4)

CL.
CL.

Reputation: 180020

SQL does not use a backslash for escaping. In SQL string literals, quotes are doubled, so you'd need to replace ' with ''.

But it would be a better idea to use parameters:

    String query = "UPDATE contacts SET name = ? WHERE phone = ?";
    db.execSQL(query, new Object[]{ newname, phone });

Upvotes: 1

Peter Pei Guo
Peter Pei Guo

Reputation: 7870

Use PreparedStatement, and should never do the quoting stuff yourself, just unnecessary trouble:

PreparedStatement pstmt = con.prepareStatement("UPDATE constacts SET name = ? WHERE phone = ?");
pstmt.setString(1, "foo")
pstmt.setString(2, '123")

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317372

Use update() to map your strings into placeholders, and Sqlite will escape the strings so that the final command is always valid.

You should always be doing this for every command.

Upvotes: 2

Shmuel
Shmuel

Reputation: 3916

Use Prepared Statements. This sanitizes the input for you before calling the sql command.

How do I use prepared statements in SQlite in Android?

Upvotes: 0

Related Questions