Database Design
Above pic shows my database design. I want to insert data into these two tables. Some part into one table and some into second table using foreign key.
Also how can i delete data from two tables at once using foreign key.
public boolean insertToBlockList(String originatingAddress,String messageBody){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(ORIGINATING_ADDRESS,originatingAddress);
contentValues.put(MESSAGE_BODY, messageBody);
db.insert(TABLE_BLOCK_LIST,null,contentValues);
return true;
i wrote this code but doesn't work for me. kindly help.
how to select and show data from these two tables using foreign key?
SELECT *
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;
Read more: http://www.w3schools.com/sql/sql_join_inner.asp
You have to execute two insert queries as told by #Prerak. However you have to use sql transactions for better result.
Related
I need help how to implement rawquery in sqlite. I need to insert a record in to specific row in table. I searched and found that I can achieve this using raw query. I am new to sqlite and don't know how to implement raw query. I got syntax error.
Here is my code
public void insert (String potision, String total, String curent)
{
SQLiteDatabase db = this.getWritableDatabase();
db.rawQuery("INSERT INTO "+Table_Name2+" VALUES(?,?) WHERE ID = ? ", new String[] {total,curent,potision});
}
Here is my syntax error:
SQLiteException: near "WHERE": syntax error (code 1): , while compiling: INSERT INTO item_counts_2 VALUES(?,?) WHERE ID = ?
Help will be appreciated
You are having a syntax error because you added a where clause to an insert.
When you execute an insert, you are adding a row to the database. There is no sense in specifying a row.
If you were updating a row, then, the where clause would be fine, because you have to tell him what row to update.
Also when deleting rows, the where clause is widely used, so that you don't erase the whole table.
Insert: official docs
Update: official docs
Delete: official docs
Note that the docs refer to SQLite, since you are using Android.
You can use update query with ContentValues to update specific row data in your DB like this
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_1, value1);
values.put(COLUMN_2, value2);
return db.update(TABLE_NAME, values, ID + " = ?",
new String[] { String.valueOf(idValue) });
Hope it will help you out.
Don't use where clause with insert query.
If you are inserting a new row to database then where clause is redundant, remove it and it will work fine.
OR,
If you want to update value already exist in database, use update query instead of insert,
for more information visit here.
I am on Android and this question is of Sqlite :
I have a table (USERLOGIN) which holds the user's credentials (username and password) in it. I have another table ($USER$_PROJS) which holds information of projects for a particular user. Users can create and add projects in there.
[ $USER$ will be a variable which comes from the column username in USERLOGIN table. So its basically a dynamic table creation. ]
Both of these tables are in the same database USER.db.
I have only one LoginDatabseAdapter class and DatabseHelper class which manages both of these.
Now initially when user logs-in, the database is behaving properly. But when inside the user profile when a user tries to create/add project its not inserting the values into $USER$_PROJS table.
I think i need to use the USE TABLE (once the user successfully logs-in his profile) like statement but its giving an error when i try to use it.
I have searched almost all the resources on net but was unable to find the solution !!
Any help would be appreciated !!
CODE RESPONSIBLE FOR CREATING TABLE :
public void createprojtable(String u){
db.execSQL(
"create table if not exists "+u+"_PROJS(ID integer primary key autoincrement,
PROJ_NAME text,DATE text); ");
}
public void insertProjEntry(String u,String projName,
String projdate) {
//db.execSQL("use table "+u+"_PROJS;");
ContentValues newValues = new ContentValues();
newValues.put("PROJ", projName);
newValues.put("DATE", projdate);
db.insert(u+"_PROJS", null, newValues);
}
Have a look at the Cursors for Sqlite in Android. You get Cursors specific to a table. Using the Cursors you can read data from a specific table as such. While updating the data also you can specify table name as one of the parameters. So you can pretty much get what you are looking for using existing APIs.
Have a look at following links :
Android SQLite Database and ContentProvider - Tutorial
android.database.sqlite
So lets say I have this code:
SQLiteDatabase sqlDB = database.getWritableDatabase();
long iD = 0;
iD = sqlDB.insert(Table1, null, TestV);
Can I somehow rewrite this to insert into two tables instead of one? My problem is that 'values' returns 3 values from one table, and 1 value from another. Therefore, the 1 value that isn't in 'Table1' sets off an error that the column cant be found in 'Table1.' Is there a way to do this? If not then should I do two separate inserts? I am confused as how to insert data into two tables in one database (Tables are Relational: one has a foreign key).
From the documentation for INSERT in SQLite:
Note that the flowchart doesn't give you an opportunity to post into more than one table at once. SQLiteDatabase.insert() is a convenience method for using the INSERT statement.
You can simulate this using database transaction:
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
db.execSQL("insert into table1...");
db.execSQL("insert into table2...");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
You may need to choose the order of the inserts if there are dependencies between the values inserted, for instance if there's a foreign key relationship: ( insert to table1 and then table2, or first insert to table2...)
I wanted to insert different values to, two different sqlite tables from a single insert query.Can any one help me out...........
Why can't you do it in two lines?? Programme will execute one after another.
You can do something as below
dbHelper = new RdmsDbAdapter(SDCardVideoActivity.this);
dbHelper.open();
dbHelper.executeSQL("CREATE TABLE IF NOT EXISTS videos(urls text)");
dbHelper.executeSQL("insert into videos values ('"+outputfilepathVideo+"', '"+IncidentFormActivity.incident_id+"')");
dbHelper.executeSQL("CREATE TABLE IF NOT EXISTS audios(urls text)");
dbHelper.executeSQL("insert into audios values ('"+outputfilepathAudio+"', '"+IncidentFormActivity.incident_id+"')");
dbHelper.close();
Learn on how to handle sqlite with Android here.
I am new to android and i have just learned how to use the database and i have a couple of questions:
How can we apply keys on the data in the database in android just like we give in Oracle database? Is it possible? If no please tell me why.
When i am deleting the first row in a database (Whose id is '1') the below rows id's are not coming in serial number i.e., id for the second row (Now first row) is '2' why not '1'.
Thank you
ok, from first,
"How can we apply keys on the data in the database in android just like we give in Oracle database? Is it possible? If no please tell me why."
Ans - We can apply the all rule which one applies to a any other database, like oracle, mysql etc... So you can have both concept of primary key and foreign key in Android's SQLite database.
2.When i am deleting the first row in a database (Whose id is '1') the below rows id's are not coming in serial number i.e., id for the second row (Now first row) is '2' why not '1'?
Ans : as per the database rules whenever you delete any records from row then its key is remains same, its not changed and whatever data after that records are also has a same key or ID so whenever you want to access that data the ID or key remain same.
EDIT: and If you want to modify that key or ID you can use UPDATE query for that.
EDIT: update(String table, ContentValues values, String whereClause, String[] whereArgs)
Updating Values
To execute an update statement, we have two ways:
1. To execute db.execSQL
2. To execute db.update method:
public int UpdateEmp(Employee emp)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(colName, emp.getName());
cv.put(colAge, emp.getAge());
cv.put(colDept, emp.getDept());
return db.update(employeeTable, cv, colID+"=?",
new String []{String.valueOf(emp.getID())});
}
The update method has the following parameters:
1. String Table: The table to update a value in
2. ContentValues cv: The content values object that has the new values
3. String where clause: The WHERE clause to specify which record to update
4. String[] args: The arguments of the WHERE clause
Convenience method for updating rows in the database.
Hope you will understand it.
Thanks,