Converting a string to char array

584 Views Asked by At

I couldn't find a perfect title for the problem but here it comes..Is there a way in which a string "hello" can be changed into a 'hello' in java (android)?? This is to make my sql query work. For example, here's my function written in java for an android app

public Cursor GetLecture(String course_code)
{
    SQLiteDatabase sqldb = this.getReadableDatabase();
    String query = "SELECT * FROM Lecture WHERE course_code =" + course_code;
    Cursor C = sqldb.rawQuery(query, null);
    return C;
}

The problem here is that what the query needs is for the value of the course_code to be for instance 'S11'and not "S11" which the variable course_code has as it is a string..So how can I change the string value which has double quote ("") to single quote ('') to make the query work? Is there a shorter way or I have to change the whole algorithm?? Thanks in advance for considering!!

3

There are 3 best solutions below

0
Mefistofel On BEST ANSWER

There is a special construction to make the values ​​in the query:

p_query = "select * from mutable where name_field = ?";
mDb.rawQuery(p_query, new String[] { fieldValue });

or you can simply add escape symbols and quotes

String query = "SELECT * FROM Lecture WHERE course_code = \"" + DatabaseUtils.sqlEscapeString(course_code) + "\"";

from here:

Android quotes within an sql query string

1
Rohit Jain On

Strings are sequence of characters delimited by double quotes. You can't delimit them by single quotes. Those are for characters. This one is in Java.

In case of SQL query, to enclose your string in single quotes, you can do it like this:

String query = "SELECT * FROM Lecture WHERE course_code = '" + course_code + "'";
0
Sergiu On

If you rewrite :

String query = "SELECT * FROM Lecture WHERE course_code =" + course_code; 

as

String query = "SELECT * FROM Lecture WHERE course_code ='" + course_code + "'";