如何在SQLite中创建两个表并使用insertData作为两个?

时间:2017-06-29 18:56:35

标签: java android sql android-sqlite

我正在开发一个浏览器并创建了一个表来保存收藏夹,现在我打算创建历史记录,我创建了一个新表但错误,在logCat中表示该表不存在,任何人都可以帮助我吗? / p>

    package br.wds.yourbrowser;

import android.content.*;
import android.database.sqlite.*;
import android.support.v4.view.*;

public class DataBaseHelper extends SQLiteOpenHelper
{

    public static final String DATABASE_NAME="favoritos.db";
    public static final String TABLE_NAME="favoritos";
    public static final String TABLE_NAME_TWO="historicos";
        public static final String COL_1="ID";
    public static final String COL_2="NAME";
    public static final String COL_3="LINK";   
    public static final String COL_HIS_1="PAGE";
    public static final String COL_HIS_2="URL";

    public DataBaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null,1);
    }
    @Override
    public void onCreate(SQLiteDatabase db)
    {
        db.execSQL("CREATE TABLE " + TABLE_NAME+ "(" + "_ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, LINK TEXT)");
        db.execSQL("CREATE TABLE " + TABLE_NAME_TWO+ "(" + "_ID INTEGER PRIMARY KEY AUTOINCREMENT, PAGE TEXT, URL TEXT)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
        db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME_TWO);
    }

    public boolean insertData(String name, String link, String page, String url)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransaction();
        try{
        ContentValues cv = new ContentValues();
        cv.put(COL_2, name);
        cv.put(COL_3, link);

       final long result = db.insert(TABLE_NAME,null,cv);

        ContentValues cvs = new ContentValues();
        cvs.put(COL_HIS_1, page);
        cvs.put(COL_HIS_2, url);

     final   long re = db.insert(TABLE_NAME_TWO,null,cvs);
        db.setTransactionSuccessful();
        db.close();


        }catch(SQLiteException e){

        }
            finally{
            db.endTransaction();
        }       
        return false;
    }
 }

1 个答案:

答案 0 :(得分:0)

可能是onUpgrade方法正在删除表,而你不是用新结构再次创建它们。因此,您可以删除它们并重新创建onUpgrade,但会丢失数据或使用sql命令ALTER TABLE添加列或您想要的任何更改。我希望这会有所帮助。