this is my code :
SQLiteDatabase.loadLibs(this);
File databaseFile = getDatabasePath("db");
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databaseFile, "Ab61", null);
database.execSQL("drop table comments");
database.execSQL("CREATE TABLE IF NOT EXISTS comments(_id INTEGER PRIMARY KEY,spot_id INTEGER,server_id INTEGER" +
",description TEXT,uid TEXT ,dates TEXT,name TEXT)");
database.execSQL("insert into comments values (null, 34, 3, 'asdasd', 'asdsad', 'asda', 'asds');");
Cursor ss=db.rawQuery("SELECT * from comments", null);
Log.v("this",Integer.toString(ss.getCount()));
I've db database ,it's an sqlite database . this is a test code so , I remove the whole database ,create it again and insert a new row .
It doesn't get any error .
the cursor getCount return 0 , it means there is nothing added to database .
It driving me crazy :(
could you help me ?
You are inserting the data into a different database (database) than that which you are querying (db).
private void InitializeSQLCipher(){
try {
SQLiteDatabase.loadLibs(getApplicationContext());
}
catch (Exception e) {
e.printStackTrace();
}
File databaseFile = getDatabasePath("demo.db");
databaseFile.mkdirs();
databaseFile.delete();
database = SQLiteDatabase.openOrCreateDatabase(databaseFile, "test123", null);
database.execSQL("create table t1(a, b)");
database.execSQL("insert into t1(a, b) values(?, ?)", new Object[]{"one for the money","two for the show"});
}
Cursor c = null;
c = database.rawQuery("SELECT a,b from t1", null);
if (c != null){
if(c.moveToFirst()){
while(!c.isAfterLast()){
//Log.e("xlcx", c.getString(c.getColumnIndex("a")));
Log.d("xlcx", c.getString(c.getColumnIndex("b")));
c.moveToNext();
}
}
}
please refer
http://androidjug.blogspot.in/2014/07/sqlcipher-for-android-application.html
Related
I have wrote those lines of code to be able to add something in my SQL DB by using "external" values. Does anyone knows how can I delete something from my DB by using again external values?
My Code to add:
String UserName = "AnyName";
String UserAge = "AnyAge";
try {
myDatabase = this.openOrCreateDatabase("Users", MODE_PRIVATE, null);
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS users (name VARCHAR, age VARCHAR)");
SQLiteStatement statement = myDatabase.compileStatement("INSERT INTO users (name, age) VALUES(?, ?)");
statement.bindString(1, UserName);
statement.bindString(2, UserAge);
statement.execute();
}catch (Exception e){
e.printStackTrace();
}
You can directly delete with database instance using delete method like below
String UserName = "AnyName";
String UserAge = "AnyAge";
myDatabase = this.openOrCreateDatabase("Users", MODE_PRIVATE, null);
myDatabase.delete("users", "name =? AND age =?" , new String[]{UserName, UserAge});
This is my database
public void DBCreate() {
SQLITEDATABASE = getActivity().openOrCreateDatabase("FavoritesDB", Context.MODE_PRIVATE, null);
SQLITEDATABASE.execSQL("CREATE TABLE IF NOT EXISTS favorite(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, word VARCHAR, meaning VARCHAR);");
}
This is how I am creating new rows:
String query = "INSERT INTO favorite (word,meaning) VALUES('"+wordd+"', '"+mean+"');";
Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", null);
if (c.moveToFirst())
{
Toast.makeText(getActivity(),"inserted",Toast.LENGTH_LONG).show();
SQLITEDATABASE.execSQL(query);
}
else
{
Toast.makeText(getActivity(),"exists",Toast.LENGTH_LONG).show();
}
How to check data before inserting value into table?
before inserting perform select query and check the cursor size if it is >0 than record already exist .
I am not sure why are you passing null in your query
Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", null);
instead
Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", new String[]{"your id1"});
or
if you want to select all record then
Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite");
try this code:
Cursor c = SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", new String[]{"your_id_name"});
Log("Cursor Count : " + c.getCount());
if(c.getCount()>0)
{
Toast.makeText(getActivity(),"exists",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getActivity(),"inserted",Toast.LENGTH_LONG).show();
SQLITEDATABASE.execSQL(query);
}
And your select query should look like:
String sql ="SELECT PID FROM "+TableName+" WHERE PID="+pidValue;
Options:
If you do not want to repeat any of the values in a column, set the column setting in the CREATE method to "UNIQUE" or even "PRIMARY KEY" if the content should be the primary key to recognize. Thus you can probably avoid any repetitions without having to check.
Loop through the table:
Cursor c = SQLITEDATABASE.rawQuery("SELECT * FROM favorite", null);
if (c.getCount() > 0) {
String searchString = "some word"; // word you are about to insert
while (c.moveToNext()) {
c.moveToFirst();
int colIndex = c.getColumnIndex("word");
String wordInCurrentRow = c.getString(colIndex);
if (!(wordInCurrentRow.equals(searchString))) {
// insert method
} else {
// do nothing
Log.d("word already existing", "nothing to insert");
}
}
}
I have done a lot of research and was unable to find a suitable method to delete all the tables in an SQLite database. Finally, I did a code to get all table names from the database and I tried to delete the tables using the retrieved table names one by one. It didn't work as well.
Please suggest me a method to delete all tables from the database.
This is the code that I used:
public void deleteall(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
do
{
db.delete(c.getString(0),null,null);
}while (c.moveToNext());
}
function deleteall() is called on button click whos code is given as below:
public void ButtonClick(View view)
{
String Button_text;
Button_text = ((Button) view).getText().toString();
if(Button_text.equals("Delete Database"))
{
DatabaseHelper a = new DatabaseHelper(this);
a.deleteall();
Toast.makeText(getApplicationContext(), "Database Deleted Succesfully!", Toast.LENGTH_SHORT).show();
}}
Use DROP TABLE:
// query to obtain the names of all tables in your database
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
List<String> tables = new ArrayList<>();
// iterate over the result set, adding every table name to a list
while (c.moveToNext()) {
tables.add(c.getString(0));
}
// call DROP TABLE on every table name
for (String table : tables) {
String dropQuery = "DROP TABLE IF EXISTS " + table;
db.execSQL(dropQuery);
}
Tim Biegeleisen's answer almost worked for me, but because I used AUTOINCREMENT primary keys in my tables, there was a table called sqlite_sequence. SQLite would crash when the routine tried to drop that table. I couldn't catch the exception either. Looking at https://www.sqlite.org/fileformat.html#internal_schema_objects, I learned that there could be several of these internal schema tables that I shouldn't drop. The documentation says that any of these tables have names beginning with sqlite_ so I wrote this method
private void dropAllUserTables(SQLiteDatabase db) {
Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
//noinspection TryFinallyCanBeTryWithResources not available with API < 19
try {
List<String> tables = new ArrayList<>(cursor.getCount());
while (cursor.moveToNext()) {
tables.add(cursor.getString(0));
}
for (String table : tables) {
if (table.startsWith("sqlite_")) {
continue;
}
db.execSQL("DROP TABLE IF EXISTS " + table);
Log.v(LOG_TAG, "Dropped table " + table);
}
} finally {
cursor.close();
}
}
delete database instead of deleting tables and then create new with same name if you need. use following code
context.deleteDatabase(DATABASE_NAME);
or
context.deleteDatabase(path);
For me, the working solution is:
Cursor c = db.rawQuery(
"SELECT name FROM sqlite_master WHERE type IS 'table'" +
" AND name NOT IN ('sqlite_master', 'sqlite_sequence')",
null
);
if(c.moveToFirst()){
do{
db.execSQL("DROP TABLE " + c.getString(c.getColumnIndex("name")));
}while(c.moveToNext());
}
Hi can anyone please help me with below error in android sqlite ? really appreciate!
Caused by: android.database.sqlite.SQLiteException: no such column: House (code 1): , while compiling: select * from category where category =House
below is part of my code in which I have inserted "House" in the table
public void onCreate(SQLiteDatabase db) {
String CREATE_CATEGORY_TABLE = "CREATE TABLE category( " +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"category TEXT UNIQUE)";
db.execSQL(CREATE_CATEGORY_TABLE);
}
public void addCategory(String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("category", name);
db.insert(CATEGORY_TABLE, // table
null, //nullColumnHack
cv); // key/value -> keys = column names/ values = column values
db.close();}
public List getCategory(){
List<String> list=new LinkedList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor =
db.rawQuery("select * from category where category =house" , null);
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
do {
String s = (cursor.getString(1));
list.add(s);
}while (cursor.moveToNext());
return list;
}
You need to wrap house with single quotes
db.rawQuery("select * from category where category = 'house'" , null);
In my case error was in trigger I wrote on table insert and update
I have an idless database in my application. How can I delete any of the rows? My database code is as follows:
mydb=Nickname.this.openOrCreateDatabase("private", 0, null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS numbers(nickname varchar,number INT(13))");
Anyone know how it is possible?
mydb=Clear.this.openOrCreateDatabase("private", 0, null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS numbers(_id INTEGER PRIMARY KEY,nickname varchar,number INT(13))");
mydb.execSQL("DELETE FROM numbers WHERE id='=?' AND number='"+num+"'");
//num is string which contains which number i wish to delete
The SQLDatabase object has a delete method. public int delete (String table, String whereClause, String[] whereArgs)
mydb.delete(TABLE, "nickname = "+ DatabaseUtils.sqlEscapeString(name), null);
mydb.execSQL("DELETE FROM your_db.your_table WHERE <write your SQL conditions here> ");