如何删除数据库并将其创建为新数据库

时间:2014-04-11 06:36:17

标签: android database loops

我正在尝试运行此代码:

for(int i=1; i <= 48; i++) { insertdiary("", ""); }

MyDBhelper文件中创建数据库时:

...
 @Override
public void onCreate(SQLiteDatabase db) {
    Log.v("MyDBhelper onCreate","Creating all the tables");



    try {
        db.execSQL(CREATE_TABLE);


        for(int i=1; i <= 48; i++) { insertdiary("", ""); } 
    }

    catch(SQLiteException ex) {
        Log.v("Create table exception", ex.getMessage());

    }

}
...

但由于某种原因,循环不会创建新行。我认为这可能是因为数据库已经存在且代码未启动。我可能错了,这可能是由于其他原因造成的。无论如何,知道如何删除和重新创建我的数据库会很棒。更新数据库版本并不会冻结我的应用程序。

编辑---------------------------------------------- -----------------------------------------

这是带有新代码的MyDBhelper文件:

package com.cookbook.data;





import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class MyDBhelper extends SQLiteOpenHelper{

private SQLiteDatabase db;
private static final String CREATE_TABLE="create table "+
Constants.TABLE_NAME+" ("+
Constants.KEY_ID+" integer primary key autoincrement, "+
Constants.TITLE_NAME+" text not null, "+
Constants.CONTENT_NAME+" text not null, "+
Constants.DATE_NAME+" long);";



// database initialization
public MyDBhelper(Context context, String name, CursorFactory factory,
                    int version) {
    super(context, name, factory, version);

}

public void drop() {
drop tables diaries;
}

@Override
public void onCreate(SQLiteDatabase db) {
    Log.v("MyDBhelper onCreate","Creating all the tables");



    try {
        db.execSQL(CREATE_TABLE);


        for(int i=1; i <= 48; i++) { insertdiary("", ""); } 
    }

    catch(SQLiteException ex) {
        Log.v("Create table exception", ex.getMessage());

    }

}

// Saves a diary entry to the database as name-value pairs in ContentValues instance
    // then passes the data to the SQLitedatabase instance to do an insert
    public long insertdiary(String title, String content)
    {

        try{
            ContentValues newTaskValue = new ContentValues();
            newTaskValue.put(Constants.TITLE_NAME,  title);
            newTaskValue.put(Constants.CONTENT_NAME, content);
            newTaskValue.put(Constants.DATE_NAME, java.lang.System.currentTimeMillis());            
            return db.insert(Constants.TABLE_NAME,  null, newTaskValue);
        } catch(SQLiteException ex) {
            Log.v("Insert into database exception caught",
                    ex.getMessage());
            return -1;
        }

    }

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
                        int newVersion) {
    Log.w("TaskDBAdapter", "Upgrading from version "+oldVersion
                            +" to "+newVersion
                            +", which will destroy all old data");
    db.execSQL("drop table if exists "+Constants.TABLE_NAME);
    onCreate(db);
}




}

编辑---------------------------------------------- --------------------------------------- Constants.java

package com.cookbook.data;

public class Constants {
public static final String DATABASE_NAME="datastorage";
public static final int DATABASE_VERSION=1;
public static final String TABLE_NAME="diaries";
public static final String TITLE_NAME="title";
public static final String CONTENT_NAME="content";
public static final String DATE_NAME="recorddate";
public static final String KEY_ID="_id";
public static final String TABLE_ROW="row_id";

}

编辑---------------------------------------------- --------------------------- LogCat

04-11 12:31:24.379: I/ActivityThread(8459): Pub com.example.classorganizer:     com.example.classorganizer.DiaryContentProvider
04-11 12:31:24.509: V/MyDBhelper onCreate(8459): Creating all the tables
04-11 12:31:24.529: W/dalvikvm(8459): threadid=1: thread exiting with uncaught exception     (group=0x40018578)
04-11 12:31:24.539: E/AndroidRuntime(8459): FATAL EXCEPTION: main
04-11 12:31:24.539: E/AndroidRuntime(8459): java.lang.RuntimeException: Unable to get     provider com.example.classorganizer.DiaryContentProvider: java.lang.IllegalStateException:     getWritableDatabase called recursively
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     android.app.ActivityThread.installProvider(ActivityThread.java:3561)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     android.app.ActivityThread.installContentProviders(ActivityThread.java:3313)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     android.app.ActivityThread.handleBindApplication(ActivityThread.java:3269)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     android.app.ActivityThread.access$2200(ActivityThread.java:117)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     android.app.ActivityThread$H.handleMessage(ActivityThread.java:973)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     android.os.Handler.dispatchMessage(Handler.java:99)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     android.os.Looper.loop(Looper.java:130)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     android.app.ActivityThread.main(ActivityThread.java:3687)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     java.lang.reflect.Method.invokeNative(Native Method)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     java.lang.reflect.Method.invoke(Method.java:507)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     dalvik.system.NativeStart.main(Native Method)
04-11 12:31:24.539: E/AndroidRuntime(8459): Caused by: java.lang.IllegalStateException:     getWritableDatabase called recursively
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:101)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     com.cookbook.data.MyDBhelper.insertdiary(MyDBhelper.java:62)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     com.cookbook.data.MyDBhelper.onCreate(MyDBhelper.java:45)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:126)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     com.cookbook.data.MyDB.open(MyDB.java:39)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     com.example.classorganizer.DiaryContentProvider.onCreate(DiaryContentProvider.java:36)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     android.content.ContentProvider.attachInfo(ContentProvider.java:840)
04-11 12:31:24.539: E/AndroidRuntime(8459):     at     android.app.ActivityThread.installProvider(ActivityThread.java:3558)
04-11 12:31:24.539: E/AndroidRuntime(8459):     ... 12 more

编辑---------------------------------------------- -------------------------------------- MyDB.class

package com.cookbook.data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;

public class MyDB {
private SQLiteDatabase db;
private final Context context;
private final MyDBhelper dbhelper;



// Initializes MyDBHelper instance
public MyDB(Context c){

    context = c;
    dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
                                            Constants.DATABASE_VERSION);

}


// Closes the database connection
public void close()
{
    db.close();

}

// Initializes a SQLiteDatabase instance using MyDBhelper
public void open() throws SQLiteException
{

    try {
        db = dbhelper.getWritableDatabase();
    } catch(SQLiteException ex) {
        Log.v("Open database exception caught", ex.getMessage());
        db = dbhelper.getReadableDatabase();
    }

}

// updates a diary entry (existing row)
    public boolean updateDiaryEntry(String title, long rowId)
    {

        ContentValues newValue = new ContentValues();
        newValue.put(Constants.TITLE_NAME, title);

        return db.update(Constants.TABLE_NAME, newValue, Constants.KEY_ID + "=" +     rowId, null)>0;

    }

// Reads the diary entries from database, saves them in a Cursor class and returns     it from the method
public Cursor getdiaries()
{
    Cursor c = db.query(Constants.TABLE_NAME, null, null,
                        null, null, null, null);
    return c;
}

}

编辑---------------------------------------------- -------------------------------------- 新错误logcat

04-11 13:26:55.699: I/ActivityThread(9752): Pub com.example.classorganizer:     com.example.classorganizer.DiaryContentProvider
04-11 13:26:55.809: V/MyDBhelper onCreate(9752): Creating all the tables
04-11 13:26:55.839: W/dalvikvm(9752): threadid=1: thread exiting with uncaught exception     (group=0x40018578)
04-11 13:26:55.859: E/AndroidRuntime(9752): FATAL EXCEPTION: main
04-11 13:26:55.859: E/AndroidRuntime(9752): java.lang.RuntimeException: Unable to get     provider com.example.classorganizer.DiaryContentProvider: java.lang.IllegalStateException:     getWritableDatabase called recursively
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     android.app.ActivityThread.installProvider(ActivityThread.java:3561)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     android.app.ActivityThread.installContentProviders(ActivityThread.java:3313)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     android.app.ActivityThread.handleBindApplication(ActivityThread.java:3269)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     android.app.ActivityThread.access$2200(ActivityThread.java:117)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     android.app.ActivityThread$H.handleMessage(ActivityThread.java:973)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     android.os.Handler.dispatchMessage(Handler.java:99)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     android.os.Looper.loop(Looper.java:130)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     android.app.ActivityThread.main(ActivityThread.java:3687)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     java.lang.reflect.Method.invokeNative(Native Method)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     java.lang.reflect.Method.invoke(Method.java:507)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     dalvik.system.NativeStart.main(Native Method)
04-11 13:26:55.859: E/AndroidRuntime(9752): Caused by: java.lang.IllegalStateException:     getWritableDatabase called recursively
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:101)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     com.cookbook.data.MyDBhelper.insertdiary(MyDBhelper.java:64)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     com.cookbook.data.MyDBhelper.onCreate(MyDBhelper.java:47)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:126)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     com.cookbook.data.MyDB.open(MyDB.java:39)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     com.example.classorganizer.DiaryContentProvider.onCreate(DiaryContentProvider.java:36)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     android.content.ContentProvider.attachInfo(ContentProvider.java:840)
04-11 13:26:55.859: E/AndroidRuntime(9752):     at     android.app.ActivityThread.installProvider(ActivityThread.java:3558)
04-11 13:26:55.859: E/AndroidRuntime(9752):     ... 12 more

1 个答案:

答案 0 :(得分:0)

您可以按照以下方式删除您的表格,

public void dropTable() 
{
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL ( "drop table diaries" );
}

上述方法也会删除您的表格和数据。但是如果您不想删除表并且只想删除记录,那么您可以尝试以下方法,

public void deleteData( String tableName ) 
{
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL ( "truncate table " + tableName );
    // db.execSQL ( "delete from " + tableName );  Using delete query
}