Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android parameterized sql query not working

Tags:

android

sqlite

If I hardcode a number into the where section I get the rows I'm expecting back

Cursor cursor = db.query( tableName, 
new String[] {colID, colString, colNumber },  
colNumber + "=14", 
null, 
null, null, null, null);

If I instead put the number in as a parameter, I don't get any rows back.

Cursor cursor = db.query( tableName, 
new String[] {colID, colString, colNumber },  
colNumber + "=?", 
new String[] { String.valueOf(14) }, 
null, null, null, null);

What am I doing wrong in the second case?

Create table statements:

db.execSQL("CREATE TABLE "
        + otherTableName + " ("
        + otherTableID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + otherTableString + " TEXT"
        + ");");

db.execSQL("CREATE TABLE "
        + tableName + " ("
        + colID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + colString + " TEXT, "
        + colNumber + " REFERENCES "
        + otherTableName + "(" + otherTableID
            + "));");
like image 698
Dan Is Fiddling By Firelight Avatar asked Feb 01 '26 22:02

Dan Is Fiddling By Firelight


1 Answers

I think that problem is your second DML statement, more accurate your declaration of foreign key. I think that it should be:

db.execSQL("CREATE TABLE "
        + tableName + " ("
        + colID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + colString + " TEXT, "
        + colNumber + " INTEGER, "
        + " FOREIGN KEY (" + colNumber + ") REFERENCES "
        + otherTableName + "(" + otherTableID
            + "));");

I cannot explain myself other reason why it's not working. Your statements are equal except one uses hardcored value and second placeholder. Probably you tried parametrized statement on tableName table where i think you declared FK incorrectly and this was reason why you got any rows.

Placeholders work based on SQLite's type affinity

If you defined column as TEXT, placeholder is replaced and value is compared as col = 'value'. If you defined column as INTEGER, placeholder is replaced and value is compared as col = value. But in your second DML statement, you didn't specified column's datatype, only that it references to some column somewhere.

like image 179
Simon Dorociak Avatar answered Feb 03 '26 12:02

Simon Dorociak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!