I was assigned to fix an Android project, and the big problem is that all sql queries to sqlite are like this
String where = " nombre = '" + txt_nombre.getText().toString().trim()+"'"
Sring sql = "SELECT * FROM TABLA1 WHERE " + where + " ; ";
Cursor mCursor = mDb.rawQuery(sql, null);
return mCursor;
As you know this causes many errors... if it is entered in
txt_nombre = ‘se introduce’’;
fails
what is the best way to solve this? (It's a whole whole project)
They also ask me to continue using Cursors.
SOLUTION
String sql = " SELECT * FROM tabla1 " ;
List<String> args = new ArrayList<>();
sql += String.format(" where %s LIKE ? ", "tabla1.descrip" );
args.add('%' + txt1.getText().toString() + '%');
String[] queryArgs = args.toArray( new String[args.size()]);
Cursor mCursor = mDb.rawQuery(strSQL, queryArgs );
PreparedStatement is used to write operations, what you have to do is write the query with '?' where the parameters go For example (from the tutorial):
And then you assign the values:
And at the end you execute it (in this case an update):
For a select query it would be analogous, executing another method:
executing another method (executeQuery):
The ResultSet (result) object is what you need to extract the data (the cursor equivalent)
You can see the complete info in the official oracle tutorial:
https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html https://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html#cursors
You can replace the characters with double quotes so that you can correctly carry out your query:
this way you would correctly create your query and get your cursor.
I found a step similar to PreparedStatement but this one uses the rawQwuey and returns the result in a CURSOR.
this is an example