The best way to avoid escaping certain characters like the % sign or the single quote (apostrophe) is to use a parameterized query. But If you prefer To escape them, here is a solution:
To illustrate the point we first create a table which has 6 columns, but in the queries we are only interested In finding the First_name while searching by Last_name:
To escape the apostrophe (single QUOTE), put 2 apostrophes next to each other:
To use a parameterized query, which Is the preferred way, the code below yields the same result:
To escape the % sign which is frequently used with the LIKE operator in a query, use this code:
The below query is not escaped, hence yields a very different recordset from the one above it:
Tags: SQLite, Escape
Libraries: SQL
To illustrate the point we first create a table which has 6 columns, but in the queries we are only interested In finding the First_name while searching by Last_name:
B4X:
txt="CREATE TABLE tblPatients (Patient_ID TEXT PRIMARY KEY, First_name TEXT,Last_name TEXT, " _
& "Address TEXT, City TEXT, Zip TEXT )"
SQL1.ExecNonQuery(txt)
txt="INSERT INTO tblPatients VALUES(?,?,?,?,?,?)"
SQL1.ExecNonQuery2(txt, Array As Object(1234,"Alex", "Smith","123 Main Street", "New York","14567"))
SQL1.ExecNonQuery2(txt, Array As Object(5000,"John", "Johnson","656 Main Blvrd", "Toronto","45670"))
SQL1.ExecNonQuery2(txt, Array As Object(9873,"Marc", "O' Riley","400 Pasadena Blvrd", "Los Angeles","04670"))
SQL1.ExecNonQuery2(txt, Array As Object(4008,"Hulk", "10% body fat","5th Avenue", "Tel Aviv","Ger49"))
SQL1.ExecNonQuery2(txt, Array As Object(2846,"Jimmy", "O' Malley","209 Carson Way", "Belfast","DD764"))
SQL1.ExecNonQuery2(txt, Array As Object(4677,"Power", "100% Super man ","Wood Circle", "Kiev","6633"))
SQL1.ExecNonQuery2(txt, Array As Object(1876,"Adam", "Osborne","671 Hiway 20 Blvrd", "Berne","SW70"))
To escape the apostrophe (single QUOTE), put 2 apostrophes next to each other:
B4X:
Dim MyQuery As String
MyQuery="SELECT * FROM tblPatients WHERE Last_name LIKE 'O''%' " ' Displays Marc and Jimmy
Cursor1=SQL1.ExecQuery(MyQuery)
For i=0 To Cursor1.RowCount-1
Cursor1.Position=i
Log ("first name: " & Cursor1.GetString("First_name"))
Next
To use a parameterized query, which Is the preferred way, the code below yields the same result:
B4X:
MyQuery="SELECT * FROM tblPatients WHERE Last_name LIKE ?"
Cursor1=SQL1.ExecQuery2(MyQuery,Array As String("O'%")) ' Displays Marc and Jimmy
To escape the % sign which is frequently used with the LIKE operator in a query, use this code:
B4X:
MyQuery="SELECT * FROM tblPatients WHERE Last_name LIKE '10\%%' ESCAPE '\'" 'Display only Hulk
Cursor1=SQL1.ExecQuery(MyQuery)
The below query is not escaped, hence yields a very different recordset from the one above it:
B4X:
MyQuery="SELECT * FROM tblPatients WHERE Last_name LIKE '10%' " 'Displays: Hulk and Power
Tags: SQLite, Escape
Libraries: SQL