user3079559
user3079559

Reputation: 417

Parsing sql strings

I have a method as below:

public boolean ReadingMade(int id, String readingdate)
{

    String selectQuery = "Select * From " + TABLE_METERREADING + " Where " +TENANTMETER_ID+ "="  +id + " And " + READINGDATE +"=" + readingdate;
    Log.e("LOG", selectQuery);      
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery(selectQuery, null);
    if(c.moveToFirst()){
        c.close();
    return true;
    }
    else
    {
        c.close();
        return false;
    }

}

I want to pass the string argument using a value from edit-text e.g

EditText readDate= (EditText)findViewById(R.id.editText1);
if (db.ReadingMade(id,readDate.getText().toString()) ==true)
        {

I get a string like one below

Select * From MeterReading Where TenantMeter_id=1 And ReadingDate=2014-01-20

Yet sq-lite expects

Select * From MeterReading Where TenantMeter_id=1 And ReadingDate='2014-01-20'

How do i pull it off?

Upvotes: 0

Views: 71

Answers (3)

laalto
laalto

Reputation: 152817

Use ? placeholders for literals to prevent the need to escape special characters in literals and to avoid SQL injection attacks:

String selectQuery = "Select * From " + TABLE_METERREADING + " Where " +TENANTMETER_ID+ "=? And " + READINGDATE +"=?";
// ...
String[] args = new String[] { Integer.toString(id), readingdate };
Cursor c = db.rawQuery(selectQuery, args);

(There's a performance benefit to ? args as well but it's normally not visible in the way Android SQLite API is used.)

Upvotes: 1

Blackbelt
Blackbelt

Reputation: 157457

If I have not misunderstood you, that should work

"='" + readingdate + "'"

Upvotes: 1

Apoorv
Apoorv

Reputation: 13520

Just change

    String selectQuery = "Select * From " + TABLE_METERREADING + " Where " +TENANTMETER_ID+ "="  +id + " And " + READINGDATE +"=" + readingdate;

to

    String selectQuery = "Select * From " + TABLE_METERREADING + " Where " +TENANTMETER_ID+ "="  +id + " And " + READINGDATE +"= '" + readingdate+"'";

Upvotes: 1

Related Questions