I have one table:
CREATE TABLE People
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name
);
I wanted to delete some rows from the table by using its id as condition. So I tried to use this one but it was not working at all. So have a look:
//idd is int
SQLiteDatabase.delete
(
"People",
"id" + " = ?",
new String[]{String.valueOf(idd)}
);
I dont know why it not working. It may because the String and int datatype. I figure it out something and it may work. But it use only two parameters instead of three. And I want to use three instead. So below is what I have figured out:
SQLiteDatabase.delete
(
"People",
"id" + " = ?" + idd,
null
);
So does anyone have any idea and help me out of this problem? I want to delete some rows from my table by using id as whereClause(second parameter) and idd variable which is integer as whereArg(3rd param) with delete function from SQLiteDatabase class.
SQLiteDatabase.delete("People", "id = " + idd, null);
Try this code
public boolean deleteTitle(Integer idd)
{
return db.delete(DATABASE_TABLE, id + "=" + idd, null) > 0;
}
Related
I have a problem to create a table. If I try to get a value from the second column, android writes a empty space in the toast. But if I try to get a value from the first column, android writes the value of the column correctly. The query functions to write the first column and to write the second column are equal. So I think the Creation of the Table is the problem. But look yourself:
public SQLiteDatabase tabelleerstellen(){
SQLiteDatabase leveldatabase = openOrCreateDatabase("leveldata.db",SQLiteDatabase.CREATE_IF_NECESSARY, null);
leveldatabase.setVersion(1);
final String CREATE_TABLE_LEVEL =
"CREATE TABLE IF NOT EXISTS tbl_level ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "ME1 TEXT, "
+ "ME2 TEXT, "
+ "ME3 TEXT, "
+ "ME4 TEXT, "
+ "ME5 TEXT, "
+ "ME6 TEXT, "
+ "ME8 TEXT, "
+ "GESCHAFFT INTEGER);";
leveldatabase.execSQL(CREATE_TABLE_LEVEL);
return leveldatabase;
}
public void tester(SQLiteDatabase leveldata){
ContentValues cursortester = new ContentValues();
cursortester.put("ME2","25");
leveldata.insert("tbl_level",null,cursortester);
String[] testerpr = {"ME2"};
Cursor testerprüfen = leveldata.query("tbl_level",testerpr,null,null, null, null,null,null);
testerprüfen.moveToFirst();
String dada = testerprüfen.getString(testerprüfen.getColumnIndex("ME2"));
Toast testertoast = Toast.makeText(getApplicationContext(),dada,Toast.LENGTH_SHORT);
testertoast.show();
}
Please check the following things:
Please make sure the table is up to date .. so try to call DROP TABLE IF EXISTS tbl_level; and recreate the table.
If you run a test make sure the table is completely empty ... so delete everything at the beggining of the test.
If the table can contain elements during the test then make sure you check the last inserted element. Please note that calling testerprüfen.moveToFirst(); moves the cursor to the first row in the table so checking that row every time is even if the table contains 50 elements is not a good thing. In this case you either use a sorting option in your query of uese while (testerprüfen != null && testerprüfen.moveToNext()) {// Your code here}
All in all I think your problem is that you already inserted more that one element in the able but you always check only the first element (with testerprüfen.moveToFirst();). Please not that there is a cursor.moveToLast() method that you can also call. This method moves the cursor to the last row in the table.
I am developing an android app where I want to delete the last row in one of my database table. I have tried the code below, but its throwing a syntax error.
public void deletelatestprofilefromsystemsettings()
{
String maxid = System_id + "="+"SELECT MAX ("+System_id+") FROM" +TABLE_SYSTEM_SETTINGS;
getWritableDatabase().delete(TABLE_SYSTEM_SETTINGS, maxid ,null);
}
Please help! Thanks!
You are lacking a space after the FROM, and subqueries must be written in parentheses:
String maxid = System_id + "=" +
"(SELECT MAX("+System_id+") FROM " + TABLE_SYSTEM_SETTINGS + ")";
You are trying to execute a DELETE with a SELECT in the same query. AFAIK you shouldn't do it. You have to execute the SELECT query first, in order to retrieve the desired id, then execute the deletion. In other words, execute Cursor c = getWritableDatabase().query(), read the id from the cursor, then use it in getWritableDatabase().delete().
Also, add a space after ") FROM", so it becomes ") FROM " in order to avoid a syntax error.
I hope anyone can help me with this.
I'm using sqlite3 on my android app. I'm trying to do this query:
mCursor = conexion.getDatabase().rawQuery("SELECT employee.name, company.name FROM employee "
+ " INNER JOIN company "
+ " ON (employee.idCompany=company._id) ORDER BY employee.name", null);
This is my schema:
CREATE table company ("_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "name TEXT NOT NULL);";
CREATE table employee ("_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "name TEXT NOT NULL, "
+ "fullName TEXT NOT NULL, "
+ "idCompany INTEGER NOT NULL, "
+ "FOREIGN KEY(idCompany) REFERENCES company (_id));";
When I run this query on my android app I get the following error:
05-09 22:35:23.170: E/AndroidRuntime(10920): FATAL EXCEPTION: main
05-09 22:35:23.170: E/AndroidRuntime(10920): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ej.ej/com.ej.ej.controlador.AplicacionActivity}: java.lang.IllegalArgumentException: column '_id' does not exist
If I run the same query but with select *:
mCursor = conexion.getDatabase().rawQuery("SELECT * FROM employee "
+ " INNER JOIN company "
+ " ON (employee.idEmployee=company._id) ORDER BY employee.name", null);
No problem I get, it works fine. But since in my schema I have name for company and name for employee I need to differentiate both.
I tried doing this query using cmd and adb commands and it works. I really don't get why the error!!
EDITED: I made it work, as #HalR suggested in the query (dont know why) I have to retrieve the ids. So now I have:
mCursor = conexion.getDatabase().rawQuery("SELECT company._id, employee.name as employee, company.name as company FROM employee "
+ " INNER JOIN company "
+ " ON (employee.idCompany=company._id) ORDER BY employee.name", null);
But I had one more issue and it wasnt in the query, it was on my ActivityFragment (thanks to #Hoan Nguyen, he made me see this part of the code again):
Listing my employees, I was getting the name of my employee and the idCompany. Don't know why, but this was looking for the _id of Company instead of idCompany of Employee.
String[] from = new String[] { "name", "idCompany"};
int[] to = new int[] { R.id.textViewNombreIzq, R.id.textViewNombreCent };
ListView lvEmployee = (ListView) view.findViewById (android.R.id.list);
ListClientsCursorAdapter notes = new ListClientsCursorAdapter(context, R.layout.activity_file_client, mCursorEmployee, from, to, 0);
lvEmployee .setAdapter(notes);
I just changed:
String[] from = new String[] { "name", "idCompany"};
For:
String[] from = new String[] { "employee", "company"};
And now is fine. Thanks to all, for your help I really apreciated :).
first, I in your CREATE TABLE employee statement you used the lable full name as a column label. If it is not a typo here, please change it to something like full_name. you can't just use spaces in column labels this way.
second, use this query string:
SELECT employee.name, company.name FROM employee INNER JOIN company ON (employee.idCompany=company._id) ORDER BY employee.name. Notice the ON expression. it's employee.idCompany not employee.idEmployee.
fix those first, and let me know if the error still exists.
I think you want this:
mCursor = conexion.getDatabase().rawQuery("SELECT employee.idCompany, employee.name, company.name FROM employee "
+ " INNER JOIN company "
+ " ON (employee.idCompany=company._id) ORDER BY employee.name", null);
Note: You need to make sure you specify the column name you are comparing in the section just after the SELECT.
Actually you don't need to name your column as _id in your table. for a example, you can create column as company_id in your company table and when you write your query, you can specify this column as below.
select company_id as _id, name from company.
Supposing I have this sqlite database structure:
ID PRODUCT_NAME AVAILABILITY
1 foo 0
2 bar 1
3 baz 0
4 faz 1
How cand I modify the value of the AVAILABILITY fom 1 -> 0 where PRODUCT_NAME = 'bar' ?
Something like this,
Pseudocod:
db.execSQL( "UPDATE TABLE" + Table_name + "MODIFY" + availability + "=" + 0 + "WHERE" + product_name + "like ? " + 'bar');
I assume that I also have to drop and recreate table using onCreate() and onUpgrade() methods, right?
Some code will be highly appreciated.
Use this:
SQLiteDatabase db=dbHelper.getWritableDatabase();
String sql="update "+Table_name+" set availability='0' where product_name like 'bar'";
Object[] bindArgs={"bar"};
try{
db.execSQL(sql, bindArgs);
return true;
}catch(SQLException ex){
Log.d(tag,"update data failure");
return false;
}
You want update not alter. alter is for the database schema, update is for the data stored in it.
For example:
update TABLE_NAME set AVAILABILITY = 0 where PRODUCT_NAME like 'bar';
Also, do not just stick strings together to build an sql query. Use a prepared statement or other statement building library to avoid SQL injection attacks and errors.
You could also use the update(), insert(), query(), delete() methods that Android gives you
// define the new value you want
ContentValues newValues = new ContentValues();
newValues.put("AVAILABILITY", 0);
// you can .put() even more here if you want to update more than 1 row
// define the WHERE clause w/o the WHERE and replace variables by ?
// Note: there are no ' ' around ? - they are added automatically
String whereClause = "PRODUCT_NAME == ?";
// now define what those ? should be
String[] whereArgs = new String[] {
// in order the ? appear
"bar"
};
int amountOfUpdatedColumns = db.update("YourTableName", newValues, whereClause, whereArgs);
The advantage here is that you get correct SQL syntax for free. It also escapes your variables which prevents bad things to happen when you use "hax ' DROP TABLE '" as argument for ?.
The only thing that is still not safe is using column LIKE ? with arguments like "hello%world_" because % (match anything of several chars) and _ (match any 1 char) are not escaped.
You would need to escape those manually (e.g. place a ! before each _ or %) and use
String whereClause = "LIKE ? ESCAPE '!'"
String[] whereArgs = new String[] {
likeEscape("bar")
// likeEscape could be replaceAll("!", "!!").replaceAll("%", "!%").replaceAll("_", "!_") maybe
}
Btw: your single code line should work if you use
db.execSQL( "UPDATE " + Table_name + " SET " + availability + "=0 WHERE " + product_name + " like 'bar'");
SqlLite uses "SQL". You need a SQL "update"
db.execSQL( "update mytable set availability=0 where product_name like '%" + bar + "%'");
Here's a good link for SQL "select", "update", "insert" and "delete" ("CRUD") commands:
http://www.w3schools.com/sql/default.asp
Im getting this error when i try to access my View
I've built my database/View using this
CREATE TABLE Boxer(
BoxerId INTEGER PRIMARY KEY AUTOINCREMENT,
Firstname NVARCHAR(50) NOT NULL,
Lastname NVARCHAR(50) NOT NULL
);
CREATE TABLE Match(
MatchId INTEGER PRIMARY KEY AUTOINCREMENT,
BoxerA INTEGER NOT NULL FOREIGN KEY REFERENCES Boxer(BoxerId),
BoxerB INTEGER NOT NULL FOREIGN KEY REFERENCES Boxer(BoxerId),
MatchDate date NOT NULL DEFAULT GETDATE(),
NumberOfRounds INTEGER NOT NULL DEFAULT 12
);
CREATE TABLE Round(
RoundId INTEGER PRIMARY KEY AUTOINCREMENT,
MatchId INTEGER NOT NULL FOREIGN KEY REFERENCES Match(MatchId),
BoxerA INTEGER NOT NULL DEFAULT 0,
BoxerB INTEGER NOT NULL DEFAULT 0,
Position INTEGER NOT NULL
);
/*
Building a view which dislpays matches with boxers names and total scores
*/
CREATE VIEW MatchDetail AS
SELECT Match.MatchId, A.BoxerId AS IdA, B.BoxerId AS IdB, A.Firstname + ' ' + A.Lastname AS NameA, B.Firstname + ' ' + B.Lastname AS NameB,
(SELECT SUM(R.BoxerA) AS Score FROM Round AS R WHERE (R.MatchId = Match.MatchId)) AS ScoreA,
(SELECT SUM(R.BoxerB) AS Score FROM Round AS R WHERE (R.MatchId = Match.MatchId)) AS ScoreB,
Match.MatchDate, Match.NumberOfRounds
FROM Boxer AS A INNER JOIN Match ON A.BoxerId = Match.BoxerA INNER JOIN Boxer AS B ON Match.BoxerB = B.BoxerId
I've pretty much built my app so far using the notepad example so I then call my DbHelper
Cursor MatchesCursor = mDbHelper.fetchAllMatchDetails();
This then calls the query
public Cursor fetchAllMatchDetails(){
return mDb.query(VIEW_MATCHDETAIL, new String[] {
"MatchId"
}, null, null, null, null, null);
}
VIEW_MATCHDETAIL is defined as a string = "MatchDetail"
and it's here where it crashes saying
no such table MatchDetail: while compiling SELECT MatchId FROM MatchDetail
anyone had this problem before?
You have some beautiful SQL there. Unfortunately only the first line of sql will be executed in SQLiteDatabase.execSQL. The rest will be ignored silently (convenient eh?). Split up the statements manually like this:
https://github.com/browep/fpt/blob/master/src/com/github/browep/nosql/NoSqlSqliteOpener.java
or if you like to keep your sql in a separate file, try this:
String sqlText = getSqlText();
for(String sqlStmt : sqlText.split(";"))
myDb.execSQL(slqStmt + ";");
What stands out to me is the use of datatypes like NVARCHAR(50). SQLite only has a very simple set of datatypes. I'm surprised it doesn't throw an exception when you install the app. Try using simply TEXT instead.
If you cannot access a database that you know you have initialized, try passing the Context from the Activity that created the table to the class trying to query the table. Use that Context as part of your connection initialization.