SQLite delete where clause arguments - java

I am new to Sqlite. Prior I tried deleting a row in my table using trick_id
public void deleteTrick (int trick_id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Constants.TRICKS_TABLE, Constants.TRICK_ID + " ?= ", new String[]{ String.valueOf(trick_id)});
db.close();
}
but now I need to delete row based on two constraints trick_id and opn_id.
How to use 'where clause' to delete the row that matches with same opn_id & trick_id that are passed in as parameters to delete method?
public void deleteTrick (int trick_id,int opn_id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Constants.TRICKS_TABLE, Constants.TRICK_ID + " ?= " WHERE Constants.OPN_ID + " ?= ", new String[]{ String.valueOf(trick_id), String.valueOf(opn_id)};
db.close();
}

to delete :
db.delete(TableName,ID_that_you_want_to_delete + " =?" , new String[]{your id that given for delete }) ;
db.delete(Constants.TRICKS_TABLE, Constants.TRICK_ID + " =? ",new String[]{String.valueOf(opn_id)})

You can use delete method like this
public void deleteTrick() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Constants.TRICKS_TABLE, null, null);
db.close();
}
In this codes first null is your WHERE clause,and second null is your Whereargs.If my answer is correct you can accept.Happy coding:)

Related

How to add a value of a variable in a sqlite database existing column?

I would like to ask for some help with my android code. I am trying to develop a quiz app using SQLite.My Database has two Tables. One for Students Information and one for the Questions and answers. Students Information such as Name, Student ID e.c. are inputs through textViews . After taking the Quiz in the Result activity the Score shown up. But i also want this score to be kept in a column COLUMN_SCORE of Student_trable.
I tried to update the table using this method:
`public static void addScore (int StudentScore){
ContentValues cv = new ContentValues();
cv.put(DataContract.StudentTable.COLUMN_SCORE, StudentScore);
Cursor c = db.rawQuery("SELECT * FROM student_info ORDER BY id DESC LIMIT 1 " ,null);
db.update(DataContract.StudentTable.TABLE_NAME1, cv, DataContract.StudentTable.COLUMN_SCORE + "= ?", new String[] {String.valueOf (c)});
db.close();`
but i failed. Any suggestion please?
Here is some more details of my code:
You can use a subquery in the WHERE clause argument of the update() method, so that there is no need for a SELECT query to retrieve the last id:
public static void addScore(int studentScore) {
String table = DataContract.StudentTable.TABLE_NAME1;
String id = DataContract.StudentTable.COLUMN_ID;
ContentValues cv = new ContentValues();
cv.put(DataContract.StudentTable.COLUMN_SCORE, studentScore);
db.update(
table,
cv,
id + " = (SELECT MAX(" + id + ") FROM " + table + ")",
null
);
db.close();
}

Cannot get the max value in a SQLite database

I am trying to get the max id of a table in SQLite in Android. This is how I get it in the database helper:
public int getMaxIncrementation() {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
String result = "0";
try{
Cursor cursor = sqLiteDatabase.rawQuery("SELECT MAX(id) FROM " +TABLE_INCREMENTATION, new String[]{});
cursor.moveToFirst();
result = cursor.getString(cursor.getColumnIndex(INCREMENTATION_ID));
}catch (Exception ex) {
Log.e("ex", ex.getMessage());
}
return Integer.parseInt(result);
};
This is how I created the table:
private static final String CREATE_TABLE_INCREMENTATION = "CREATE TABLE IF NOT EXISTS " + TABLE_INCREMENTATION
+ "("
+ INCREMENTATION_DATEADDED + " TEXT,"
+ INCREMENTATION_DIRECTION + " INTEGER,"
+ INCREMENTATION_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ INCREMENTATION_USER + " TEXT"
+ ")";
This is the snapshot of my table with data in it:
On debugging, I always get this error:
Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor
is initialized correctly before accessing data from it.
First, since you don't have in the query any ? placeholders then you don't need to pass any parameters to the sql statement, so the 2nd argument of rawQuery() should be null.
Also you must give an alias to the column that your query returns and use it to get the returned value (you can't use INCREMENTATION_ID because it is not the name of the column returned):
Cursor cursor = sqLiteDatabase.rawQuery("SELECT MAX(id) AS maxid FROM " +TABLE_INCREMENTATION, null);
if (cursor.moveToFirst())
result = cursor.getString(cursor.getColumnIndex("maxid"));
Or if you don't use an alias then use 0 as there is only 1 column returned:
Cursor cursor = sqLiteDatabase.rawQuery("SELECT MAX(id) FROM " +TABLE_INCREMENTATION, null);
if (cursor.moveToFirst())
result = cursor.getString(0);

Getting specific data by column using sqlite database

I couldn't give a good title to the problem I'm having, but basically I have two columns Name and MaxNum string and int respectively!
I need int method that makes a query which retrieves the MaxNum for specific Name that I give in parameter!
.. so if I have this data
ID | Name | MaxNum
0 | Mike | 50
1 | John | 40
2 | Jess | 30
..when I put Jess in as parameter it will return 30 !
My method so far.. but I can't use it since it doesn't return int value !
public void maxFromName(String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COLUMN_MAX + " FROM "+ TABLE_AZKAR+" WHERE " +COLUMN_NAME+ "=" + name ;
db.execSQL(query);
}
You have to get the result using
Cursor
String query = "SELECT " + COLUMN_MAX + " FROM "+ TABLE_AZKAR+" WHERE " +COLUMN_NAME+ "=" + name ;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
return c.getInt(c.getColumnIndex("MaxNum"));
Update
Since you are facing the problem, I suggest you use the below query:
String query = Select MaxNum from azkar WHERE Name ='Jess';
after this use my code from Cursor c line, this will work.
Use rawQuery for getting data from SQLite. And from the cursor get integer value using getInt function.
Change your maxFromName function with the following.
public int maxFromName(String name){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT " + COLUMN_MAX + " FROM "+ TABLE_AZKAR+" WHERE " +COLUMN_NAME+ "= '" + name +"'" ;
Cursor c = db.rawQuery(query, null);
if(c.getCount()!=0){
c.moveToFirst();
return c.getInt(c.getColumnIndex("MaxNum"))
}
return 0;
}
In the API it says the following in the description of execSQL():
Execute a single SQL statement that is NOT a SELECT or any other SQL
statement that returns data.
Use a query method that returns a Cursor type in order to retrieve results
The easiest way to get a single value from a database is with the stringForQuery() or longForQuery() helper functions:
public long maxFromName(String name) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT "+COLUMN_MAX+" FROM "+TABLE_AZKAR+" WHERE "+COLUMN_NAME+" = ?";
return DatabaseUtils.longForQuery(db, query, new String[]{ name });
}
(To prevent string formatting problems and SQL injection attacks, always use parameters instead of inserting string values directly into the query.)
You can use rawQuery
public ArrayList<String> maxFromName(String name){
ArrayList<String> maxNums = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COLUMN_MAX + " FROM "+ TABLE_AZKAR+" WHERE "
+COLUMN_NAME+ "=" + name ;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
do { // if that kind of rows are more then one, this metod get all of them
maxNums.add(c.getInt(c.getColumnIndex("MaxNum")));
}
return maxNums;
}

How to check whether there is a record satisfying some condition in a sqlite table

I have the following code
public int getIngCount(String id,String ingrediant) {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS2 + " WHERE id = "+id+ " AND ingrediant = "+ingrediant;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
// return count
return cursor.getCount();
}
But when there is no records satisfying the condition, it causing an exception (no such column) instead of returning 0.
pls help me to find a solution. Thanks in advance.
ingrediant should be treated as a string literal and not as an identifier such as a column name. In SQL you use single quotes for string literals. It's a better idea to use ? placeholders for binding literal values, though:
String countQuery = "SELECT * FROM " + TABLE_CONTACTS2 + " WHERE id = "+id+ " AND ingrediant = ?";
Cursor cursor = db.rawQuery(countQuery, new String[] { ingrediant });
Also, don't call any cursor methods after closing it.

Android SQLite SELECT Query

I have taken String value from a EditText and set it inside SELECT QUERY after WHERE condition
As
TextView tv = (TextView) findViewById(R.id.textView3);
EditTextet2 et = (EditText) findViewById(R.id.editText1);
String name = et.getText().toString();
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE name = '"+name+"'", null);
c.moveToNext();
tv.setText(c.getString(c.getColumnIndex("email")));
But it doesn't work. Any suggestions?
Try trimming the string to make sure there is no extra white space:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);
Also use c.moveToFirst() like #thinksteep mentioned.
This is a complete code for select statements.
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
do {
// Passing values
String column1 = c.getString(0);
String column2 = c.getString(1);
String column3 = c.getString(2);
// Do something Here with values
} while(c.moveToNext());
}
c.close();
db.close();
Try using the following statement:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE name = ?", new String[] {name});
Android requires that WHERE clauses compare to a ?, and you then specify an equal number of ? in the second parameter of the query (where you currently have null).
And as Nambari mentioned, you should use c.moveToFirst() rather than c.moveToNext()
Also, could there be quotations in name? That could screw things up as well.
Here is the below code.
String areaTyp = "SELECT " +AREA_TYPE + " FROM "
+ AREA_TYPE_TABLE + " where `" + TYPE + "`="
+ id;
where id is the condition on which result will be displayed.
public User searchUser(String name) {
User u = new User();
SQLiteDatabase db = this.getWritableDatabase(); //get the database that was created in this instance
Cursor c = db.rawQuery("select * from " + TABLE_NAME_User+" where username =?", new String[]{name});
if (c.moveToLast()) {
u.setUsername(c.getString(1));
u.setEmail(c.getString(1));
u.setImgUrl(c.getString(2));
u.setScoreEng(c.getString(3));
u.setScoreFr(c.getString(4));
u.setScoreSpan(c.getString(5));
u.setScoreGer(c.getString(6));
u.setLevelFr(c.getString(7));
u.setLevelEng(c.getString(8));
u.setLevelSpan(c.getString(9));
u.setLevelGer(c.getString(10));
return u;
}else {
Log.e("error not found", "user can't be found or database empty");
return u;
}
}
this is my code to select one user and one only
so you initiate an empty object of your class then
you call your writable Database
use a cursor in case there many and you need one
here you have a choice Use : 1-
if (c.moveToLast()) { } //it return the last element in that cursor
or Use : 2-
if(c.moveToFirst()) { } //return the first object in the cursor
and don't forget in case the database is empty you'll have to deal with that in my case i just return an empty object
Good Luck
Detailed answer:
String[] selectionArgs = new String[]{name};
Cursor c = db.rawQuery(
"SELECT * FROM " + tabl1 +
" WHERE " + name + " = ? ", selectionArgs
);
selectionArgs : this takes the 'name' you desire to compare with, as argrument.
Here note "A Cursor object, which is positioned before the first entry of the table you refer to".
So,to move to first entry :
c.moveToFirst();
getColumnIndex(String ColumnName) : this returns the zero-based column index for the given column name.
tv.setText(c.getString(c.getColumnIndex("email")));
In case, you want to go searching through multiple rows for a given name under 'name' column then use loop as below:
if (cursor.moveToFirst()){
do{
////go traversing through loops
}while(cursor.moveToNext());
}
This should solve the problem.

Categories

Resources