I am populating an alertDialog from my database allowing a user to select a preset email message template. The populating seems to work but I cannot delete or edit it, only add to it. I wanted to delete all the rows and basically repopulate it from the beginning but I can seem to delete a single entry or all entries.
This is my deleting method in my DB Handler class:
public void deleteAppointment() {
ourDatabase.delete(DATABASE_TABLETEMP, null, null);
}
This code I have used to try and delete all the rows but it dosent. Can anyone see where I am going wrong?
You can do:
Drop table tablename
--run rebuild scripts
Related
QUESTION:
What, if anything, could cause an SQLite trigger to only run some of the time?
SUMMARY: I'm getting seemingly inconsistent results from a new trigger I've written in SQLite and I'd like to understand if this is happening because I've made a mistake in my SQL/Java code or if I've possibly encountered a rare scenario where SQL triggers may not work as expected.
DETAILS:
While working on an Android project I have encountered what I originally perceived to be a problem with an SQLite trigger. However, since my new trigger exactly matches several other working triggers in the same project (except for the table names) I am beginning to wonder if my Java code is the issue instead.
The purpose of the trigger I am having trouble with is to monitor changes to TableA, such as the addition of a value in the DismissDateUTC column for example. When an update is made to any data in TableA, the trigger is supposed to put the ID of that updated TableA record into TableAChanges which is later used to determine which records were updated and should be sent back to a web server.
When using the database inspector (in Android Studio v4.2.1) or the program “DB Browser for SQLite” and running an update query on TableA manually, the trigger works exactly as expected and records appear in TableAChanges. When I make updates to TableA programmatically, the trigger does not appear to run. I believe it is not running because no records are written to TableAChanges after updates have been written to TableA.
Things I have tried so far:
Running the app on an Android 7.1.1 device (trigger is NOT working)
Running the app on an Android 8.1.0 device (trigger is NOT working)
Running the app on an Android 11 device (trigger is NOT working)
Running manual update query on TableA from Android Studio DB Inspector (trigger IS working)
Running manual update query on TableA from DB Browser for SQLite (trigger IS working)
Running manual update query on TableA from Android Debug Database by “amitshekhar” (trigger IS working)
The Tables and Trigger SQL:
CREATE TABLE TableA (
ID INTEGER PRIMARY KEY NOT NULL
-- (more table columns) --
, DismissDateUTC TEXT NULL
);
CREATE TABLE TableAChanges (
ID INTEGER PRIMARY KEY NOT NULL
);
CREATE TRIGGER trigTableA_U AFTER UPDATE ON TableA
BEGIN
REPLACE INTO TableAChanges(ID)
SELECT old.ID;
END
The Android Java in the TableA DAO class:
public boolean saveChanges() {
boolean ret = true;
ContentValues cv = new ContentValues();
cv.put("ID", mId);
// (more table columns)
cv.put("DismissDateUtc", mDismissDateUtc);
SQLiteDatabase db = DB.getInstance().getWritableDatabase();
try {
db.replaceOrThrow("TableA", null, cv);
} catch (SQLException e) {
ExceptionDao.logToAcra(e);
ret = false;
} finally {
db.close();
}
return ret;
}
*** In the interest of transparency, I am already aware that I can work around this issue by manually writing records to TableAChanges. However, I still wanted to post this question here because I am hoping to gain an understanding of the cause of this issue rather than ignoring the issue.
The reason that the trigger does not work is because it is an AFTER UPDATE trigger, which means that it will work only after the table is updated.
On the other hand, replaceOrThrow() does not update the table.
It is actually executing an INSERT OR REPLACE INTO... or simply REPLACE INTO... statement which either inserts a new row in the table if the new ID does not already exist in the table, or if it exists, deletes the row that contains the existing ID and inserts the new row.
final SQLiteDatabase mydb = openOrCreateDatabase("phone_calls",MODE_PRIVATE,null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS Numbers(PhoneNumber VARCHAR,FullName VARCHAR,Cost VARCHAR );");
mydb.execSQL("CREATE TABLE IF NOT EXISTS Calls(FromNum VARCHAR,ToNum VARCHAR,duration VARCHAR );");
Ive created this sqlite in Activity 1. i inserted some data to the first table in first activity.
now i created a second activity and i want to insert data to the other table?what shall i do? create the database again in the second activity and insert in it? or is there any other way?
First of all, you should read the docs - https://developer.android.com/training/basics/data-storage/databases.html
Next, you should try to write simple application in order to use new knowledge.
If it fails, then post the question with more code and Logcat output.
Just create a database helper class which will create all your tables,
then create needed methods like saveObject(YourObject), deleteObject(id),
etc...
Make your helper singleton and initiate it once in Application in onCreate()
and just use it in your activities.
For example you can look here: https://gist.github.com/mikeplate/9173040
I have an app on playstore which contains a database.
Now in the new release, database is changed, a new table is entered.
Currently i am using sqlite studio and put the database file in the assets which is later copied as an app database. See this example.
I have to delete the previous database to copy new, or if i copy new(overwrite), in both cases user data is lost.
Maybe i can attach a new table to current database, but what if i have to add a column in table in previous database???
How should i handle this???
Edit: If i have to copy the data from database and re-insert, how can i know the tables and columns which currently exist in my database.
Please guide me...
Get All the data from Database into ArrayList or anything else (I will suggest Arraylist) and Delete old database and then Create New database and Insert all The data into New database.
Its not a Proper way but a trick to save your time.
Cheers
-Aman
For a new Table, you just have to add the create table in the update method
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
if(oldVersion < LastVersionWithoutTheTable && newVersion >= LastVersionWithoutTheTable){
db.execSQL(CREATE_THE_TABLE);
}
}
For a new column, copy all your data in an array, recreate your table and insert your data again.
It's maybe possible to used SQL Alter Table but I never try it on a SQlite database.
I'm currently using Java to access a .sql file (called patient.sql). Running queries and updating the table works well while the program is running, but the changes aren't made on disk.
So, for example, I have a 30 node database with some fields including caseID (primary key) and Hospital. I want to change the Hospital of the node with caseID = Case29. To do this, I use the following code:
// Prepare a statement to update a record
String sql = "UPDATE patient SET Hospital='CX' WHERE caseID = 'Case29'";
// Execute the insert statement
stmt.executeUpdate(sql);
I have checked this and seen that it works (using a quick System.out.println()). However, when I finish the program and open the patient.sql, my change has not been registered. How can I save this change made?
Cheers
EDIT: I'm using HSQLDB
If you are using HSQLDB changes are stored in a .log file until SHUTDOWN is called.
After a SHUTDOWN, all changes are moved to a .script file.
One description of HSQLDB files here:
http://hsqldb.org/doc/guide/ch01.html
In your case I suspect no SHUTDOWN has been called.
I am attempting to create a test database (based off of my production db) at runtime, but rather than have to maintain an exact duplicate test db i'd like to copy the entire data structure of my production db at runtime and then when I close the test database, drop the entire database.
I assume I will be using statements such as:
CREATE DATABASE test //to create the test db
CREATE TABLE test.sampleTable LIKE production.sampleTable //to create each table
And when I am finished with the test db, calling a close method will run something like:
DROP DATABASE test //delete the database and all its tables
But how do I go about automatically finding all the tables within the production database without having to manually write them out. The idea is that I can manipulate my production db without having to be concerned with maintaining the structure identically within the test db.
Would a stored procedure be necessary in this case? Some sample code on how to achieve something like this would be appreciated.
If the database driver you are using supports it, you can use DatabaseMetaData#getTables to get the list of tables for a schema. You can get access to DatabaseMetaData from Connection#getMetaData.
In your scripting language, you call "SHOW TABLES" on the database you want to copy. Reading that result set a row at a time, your program puts the name of the table into a variable (let's call it $tablename) and can generate the sql: "CREATE TABLE test.$tablename LIKE production.$tablename". Iterate through the result set and you're done.
(You won't get foreign key constraints that way, but maybe you don't need those. If you do, you can run "SHOW CREATE TABLE $tablename" and parse the results to pick out the constraints.)
I don't have a code snippet for java, but here is one for perl that you could treat as pseudo-code:
$ref = $dbh->selectall_arrayref("SHOW TABLES");
unless(defined ($ref)){
print "Nothing found\n";
} else {
foreach my $row_ref (#{$ref}){
push(#tables, $row_ref->[0]);
}
}
The foreach statement iterates over the result set in an array reference returned by the database interface library. The push statement puts the first element of the current row of the result set into an array variable #tables. You'd be using the database library appropriate for your language of choice.
I would use mysqldump : http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html
It will produce a file containing all the sql commands needed to replicate the prod database
The solutions was as follows:
private static final String SQL_CREATE_TEST_DB = "CREATE DATABASE test";
private static final String SQL_PROD_TABLES = "SHOW TABLES IN production";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.execute(SQL_CREATE_TEST_DB);
SqlRowSet result = jdbcTemplate.queryForRowSet(SQL_PROD_TABLES);
while(result.next()) {
String tableName = result.getString(result.getMetaData().getColumnName(1)); //Retrieves table name from column 1
jdbcTemplate.execute("CREATE TABLE test2." + tableName + " LIKE production." + tableName); //Create new table in test2 based on production structure
}
This is using Spring to simplify the database connection etc, but the real magic is in the SQL statements. As mentioned by D Mac, this will not copy foreign key constraints, but that can be achieved by running another SQL statement and parsing the results.