将数据添加到SQLite数据库只能一次性和多次读取 [英] Add data to sqlite database only onetime and read multiple times

查看:853
本文介绍了将数据添加到SQLite数据库只能一次性和多次读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的 sqlite的。在我的Andr​​oid项目,我有我只需要一次性添加这些数据到应用程序的数据库。(不要插入数据每次,应用程序运行时)。我怎样才能实现这个任务?

I'm new to the sqlite. In my android project, I have a database which I need to add those data only onetime to the app.(do not insert data everytime, when app runs). How can I achieve this task?

我试图与创建

public class DatabaseHandler extends SQLiteOpenHelper {

}

MainActivity

推荐答案

有一个调用一次,只有一次前所未有的方法,它是在的onCreate 方式。所以,如果你需要DATAS添加到数据库只有一次,你必须这样做,这个方法中。

in SQLiteOpenHelper there is a method that called once and just once ever, it's the onCreate method. so if you need to add datas to DB only one time you have to do it inside this method.

但是,如果由于某种原因,你想更多DATAS添加到数据库,你可以做它的 onUpgrade 方式这个时候。

But if for some reason you want to add more datas to the DB you could do it in onUpgrade method this time.

利用这个简单的例子:

public class DatabaseHandler extends SQLiteOpenHelper {

  private static final String DATABASE_NAME = "dbName";
  private static final int DATABASE_VERSION = 1;

  private static final String TABLE_NAME = "tableName";

  public MySQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  //this function called only once ever in the life of the app
  @Override
  public void onCreate(SQLiteDatabase database) {
    //Create database query
    database.execSQL("create table " + TABLE_NAME + " (column1 type, columun2 type...); ");

    //Insert query
    database.execSQL("insert into " + TABLE_NAME + " values(value1,value2...);");
    database.execSQL("insert into " + TABLE_NAME + " values(value1,value2...);");
    database.execSQL("insert into " + TABLE_NAME + " values(value1,value2...);");
    database.execSQL("insert into " + TABLE_NAME + " values(value1,value2...);");
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    //add more insert query if you need to add more datas after, but you have first to upgrade your DATABASE_VERSION to a higher number
  }

}

这篇关于将数据添加到SQLite数据库只能一次性和多次读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆