How to add column in an existing table? I used the following code.
SQLiteDatabase db = this.getWritableDatabase();
db.rawQuery("ALTER TABLE " + MNEMONICTABLE +" ADD COLUMN " + F_STATUS +" int DEFAULT 0", null);
This code runs without error. But the new column was not added to the table.
You are using rawQuery instead of execSQL. Try this:
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("ALTER TABLE " + MNEMONICTABLE +" ADD COLUMN " + F_STATUS +" int DEFAULT 0");
you can use ALTER TABLE function on your onUpgrade() method, like this :
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// If you need to add a column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE " + MNEMONICTABLE +" ADD COLUMN " + F_STATUS +" int DEFAULT 0", null);
}
}
Obviously, the SQLite will differ depending on the column definition. Also you need to upgrade your database version.
you should COMMIT changes also
Related
I'm trying to remove a row from an SQL table using this code below. However, whenever I call this method I get this following error:
android.database.sqlite.SQLiteException: no such column: Plumber (code 1): , while compiling: DELETE FROM service WHERE name = Plumber
public boolean deleteService(String name){
SQLiteDatabase db = this.getWritableDatabase();
boolean result = false;
String query = "SELECT * FROM "
+ TABLE_SERVICE
+ " WHERE "
+ COLUMN_NAME
+ " = \""
+ name
+ "\""
;
Cursor cursor = db.rawQuery(query, null);
if(cursor.moveToFirst()){
String nameStr = cursor.getString(0);
db.delete(TABLE_SERVICE, COLUMN_NAME + " = " + nameStr, null);
cursor.close();
result = true;
}
db.close();
return result;
}
This is my table
public void onCreate(SQLiteDatabase db){
String CREATE_USERS_TABLE = "CREATE TABLE " +
TABLE_SERVICE + "("
+
COLUMN_NAME + " TEXT," +
COLUMN_RATE + " TEXT," +
COLUMN_CATEGORY + " TEXT," + COLUMN_SUBCATEGORY + " TEXT)";
db.execSQL(CREATE_USERS_TABLE);
}
First you're fetching all the rows that in COLUMN_NAME have the value name.
Next you want to delete the 1st of these rows (maybe it's the only one?) because nameStr gets the value of the 1st column which is COLUMN_NAME.
Why are you doing this?
Just execute this statement:
int number = db.delete(TABLE_SERVICE, COLUMN_NAME + " = '" + name + "'", null);
if number gets the value 0 then no rows were deleted, else it gets the number of deleted rows.
delete deletes rows not columns.
If you want to get rid of a column, you need to drop it. The SQL syntax is:
alter table table_service drop column <column_name>;
I don't know how to express this in java with the methods that you are using.
Ensure that your SQL syntax is correct, and that "Plumber" is a string with double quotes. By my experience, these errors are usually caused by an incorrect column or name.
Use this format:
DELETE FROM table_name WHERE condition(s)
SQLite browser can also help you visualize your database.
I'm newbie with Java and Android Studio.I'm currently trying to create a to do list application. For that, I need to store the user's input into a database. However I can create the database and the table without any problem. But each time I try to add new row into the database, an error occurs.
D/DatabaseHandler: ===Inside DatabaseHandler constructor===
D/DatabaseHandler: ===Inside onCreate from DatabaseHandler===
D/MainActivity: ==addToDatabase==
/SQLiteLog: (1) no such table: test_database
E/SQLiteDatabase: Error inserting STATE=14 TASK=13 ID =1
android.database.sqlite.SQLiteException: no such table: test_database (code 1): , while compiling: INSERT INTO test_database(STATE,TASK,ID ) VALUES (?,?,?)
create the database (DatabaseHandler) and create the table (onCreate()):
public class DatabaseHandler extends SQLiteOpenHelper {
public DatabaseHandler(Context context) {
super(context, "test_database", null, 1);
Log.d(TAG, "===Inside DatabaseHandler constructor===");
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "===Inside onCreate from DatabaseHandler===");
// String database_table = "CREATE TABLE task(" + COLUMN_ID + " INT NOT NULL," + COLUMN_TASK + " INT NOT NULL," + COLUMN_STATE + " INT NOT NULL)";
String database_table = "CREATE TABLE task(ID INT NOT NULL, TASK INT NOT NULL, STATE INT NOT NULL)";
db.execSQL(database_table);
}
}
and finally the function I used for add new row into the DB:
public int addToDatabase(SQLiteDatabase access, String task) {
Log.d(TAG, "==addToDatabase==");
if (access.isOpen() == false) {
Log.d(TAG, "[addToDatabase] Database is not Open");
return (-1);
}
ContentValues values = new ContentValues();
values.put("ID ", 1);
values.put("TASK", 13);
values.put("STATE", 14);
access.insert("test_database", null, values);
return (1);
I already try to solve the problem by myself by looking on the other existing post. It seem that it may be cause because the database wasn't create correctly. Nonetheless as you can there's any error while creating the database, only when I'm trying to add new stuff.
I also read that it could be in report with the version of the database...However, I don't really understand why..(I'm still looking into the official documentation).
Does anyone can explain me and tell me how can I fix the problem ?
Thanks :)
Use this
access.insert("task", null, values)
instead of this
access.insert("test_database", null, values);
or
if you have updated your app table name then uninstall your app manually and try running again.
Your table name is apparently wrong. Change the table creation query.
String database_table = "CREATE TABLE test_database(ID INT NOT NULL, TASK INT NOT NULL, STATE INT NOT NULL)";
This might help you Android Sqlite Database Tutorial
You may edit your "DatabaseHandler" and run the project so that the change in your database doesn't occur.
I simply removed data from the application, to be opened for the first time
and it worked for we:
I have a database created in android studio to save data to . The table is not being created in the database . The error I'm getting is :
03-04 00:55:45.783 25787-25787/com/SQLiteLog: (1) no such table: TableName
03-04 00:55:45.783 25787-25787/com.E/SQLiteDatabase: Error inserting
My code for creating the table is :
#Override
public void onCreate(SQLiteDatabase db) {
db = SQLiteDatabase.openOrCreateDatabase("DB.ad",null);
Log.v(TAG, "*TABLE ");
// create TableName table
db.execSQL(CREATE_TableName_TABLE);
this.checkDataBase();
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
} catch (SQLiteException e) {
// database doesn't exist yet.
}
return checkDB != null;
}
I was wondering if anyone can tell me why I am getting this error?
String CREATE_TableName_TABLE = "CREATE TABLE TableNames( " +
"Id INT( 30 ) PRIMARY KEY AUTOINCREMENT, " +
"TagNo TEXT, " +
"Description TEXT, " +
"WeeksGone INTEGER( 10 ) NOT NULL DEFAULT 0 );";
Here is an example how to create your database. First your class should extends from SQLiteOpenHelper
Then use super to SQLiteOpenHelper class with your db name and version,
public YourClassName(Context context) {
super(context, "YourDatabaseName", null, 1); // 1 is the version of the database, after each change in your db you should ++.
}
Then create your table:
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
final String SQL_CREATE_BLABLA_TABLE = "CREATE TABLE " + "TableNameHere" + " (" +
"_id" + " INTEGER PRIMARY KEY," +
"name" + " TEXT NOT NULL);";
sqLiteDatabase.execSQL(SQL_CREATE_BLABLA_TABLE);
}
And finally in case you need to upgrade your db version, because you make any change override the onUpgrade method, in order to create again the table.
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + "TableNameHere");
onCreate(sqLiteDatabase);
}
For more information of how to implement SQLite please read this.
Please review the following types in order to create your table:
1.0 Storage Classes and Datatypes
Each value stored in an SQLite database (or manipulated by the database engine) has one of the following storage classes:
NULL. The value is a NULL value.
INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number.
TEXT. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE).
BLOB. The value is a blob of data, stored exactly as it was input.
For more information of datatypes please see this link.
So your table should be create like this:
String CREATE_TableName_TABLE = "CREATE TABLE TableNames (Id INTEGER PRIMARY KEY AUTOINCREMENT, TagNo TEXT,
Description TEXT, WeeksGone INTEGER NOT NULL DEFAULT 0 );";
I am working on an android application that uses two databases. Recently, I had to add a new column to one of the databases. Upon doing so, it broke my database. Installing and re-installing the application on my device did nothing, and I also updated the DB version.
Trying to insert data will net me this error:
E/SQLiteLog﹕ (1) table message_table has no column named msg_type
So, I tried taking out the "msg_type" column from the insert, and inserting data which gave me this error:
E/SQLiteLog﹕ (1299) abort at 8 in [INSERT INTO message_table(recipient,message) VALUES (?,?)]: NOT NULL constraint failed: message_table.msg_typeTEXT
Here is the oncreate:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + //msg_id
COL_2 + " TEXT NOT NULL, " + //recipient
COL_3 + " TEXT, " + //message
COL_4 + "TEXT NOT NULL);"); //message type
}
and the insert class:
public boolean addMessage(String recipient, String message, String type){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//populate message object
contentValues.put(COL_2, recipient);
contentValues.put(COL_3, message);
contentValues.put(COL_4, type);
//insert new message
long result = db.insert(TABLE_NAME, null, contentValues);
//check if operation was successful
if(result == -1)
return false;
else
return true;
}
How can I be getting an error for either case? I thought that it didn't recognize the new column was added from the first error, but it also doesn't like not receiving the data for that column.
The error is happening because there is no space between the column name and the TEXT. So the column name becomes message_table.msg_typeTEXT:
COL_4 + "TEXT NOT NULL);"); //message type
This should fix the error:
COL_4 + " TEXT NOT NULL);"); //message type
I keep getting this error:
"table keyTable has no column named number"
Still pretty new to Android, so no clue why this happens, can anyone spot the error?
This is my Database class:
public class KeyDatabase extends SQLiteOpenHelper {
private static final String database_name = "KeyDatabase.db";
private static final int database_version = 1;
KeyDatabase (Context context){
super(context,database_name,null,database_version);
}
#Override
public void onCreate (SQLiteDatabase db){
db.execSQL("CREATE TABLE " + KeyTableClass.table_name
+ "(" + KeyTableClass.id + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KeyTableClass.number + " TEXT, "
+ KeyTableClass.key + " TEXT);");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS " + KeyTableClass.table_name);
onCreate(db);
}
public long InsertKey (String number, String key){
ContentValues valuesToInsert = new ContentValues();
valuesToInsert.put(KeyTableClass.number, number);
valuesToInsert.put(KeyTableClass.key, key);
SQLiteDatabase sd = getWritableDatabase();
long result = sd.insert(KeyTableClass.table_name, KeyTableClass.number, valuesToInsert);
return result;
}
This is my class for my table:
public class KeyTableClass {
//The name of the table
public static final String table_name = "keyTable";
//The columns of the table
public static String id = "id";
public static String number = "number";
public static String key = "key";
}
Maybe you've edited the DB onCreate but didn't let it re-run?
Try uninstalling/install the App, Or update database_version to =2.
You don't fit the requirements for the insertion :
public long insert (String table, String nullColumnHack, ContentValues values)
Added in API level 1 Convenience method for inserting a row into the
database.
Parameters table the table to insert the row into
nullColumnHack optional; may be null. SQL doesn't allow inserting a
completely empty row without naming at least one column name. If your
provided values is empty, no column names are known and an empty row
can't be inserted. If not set to null, the nullColumnHack parameter
provides the name of nullable column name to explicitly insert a NULL
into in the case where your values is empty. values this map contains
the initial column values for the row. The keys should be the column
names and the values the column values Returns the row ID of the newly
inserted row, or -1 if an error occurred
Could you try to do :
sb.insert(table_name, null, valuesToInsert);