如何将 1300 行添加到 SQLite table?

How to add 1300 rows to SQLite table?

在 Android Studio 中,我需要为城市和人口列表创建一个 SQLite table。它大约有 1300 行。该列表位于 2 列 Excel 文件中,因此我可以将其从那里复制到我的代码中。

我有一个 class 来管理数据库和一个创建 table 的方法,但我不知道如何将城市人口列表添加到 table .

这是我必须创建的代码的一部分 table:

String crearTablaCities = "CREATE TABLE "+MI_TABLA_CITIES+" (ID_CITY INTEGER PRIMARY KEY AUTOINCREMENT, NAME_CITY TEXT, POPULATION_CITY INTEGER)";
        db.execSQL(crearTablaCities);

我知道如何添加一行从某处获取值,但我不知道如何自动添加超过 1300 行,这样我就不必手动编写或修改超过 1300 行。

    public void insertCity(ObjectCity newCity){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        //cv.put("ID_CITY", newCity.getCityID());
        cv.put("NAME_CITY", newCity.getCityName());
        cv.put("POPULATION_CITY", newCity.getCityPopulation());

        db.insert(MI_TABLA_CITIES,null,cv);

        //db.close();
    }

不知道接下来要怎么面对。有人可以给我一些提示以找到方法吗?非常感谢

有 3 种相对简单的方法可以完成此操作。

a) 创建一个代您生成代码的公式,然后将生成的代码复制并粘贴到 suitable 位置。

b) 将数据保存为 csv 并将文件复制为资产,然后您可以打开并读取文件,提取数据并将其插入数据库助手的 onCreate 方法中。

c) 将数据保存为 csv 并使用 SQLite 工具导入和加载数据,然后将该数据库复制为资产,然后使用该数据库。

选项 A 非常简单,假设您有类似的东西:-

并且您的代码表明您有一个采用 City 对象的 insertCity 方法。假设您使用 City("Tokyo",37339804) 构建一个城市,然后插入一个城市,您的代码可能类似于:-

`insert(new ObjectCity("Tokyo",37339804L));`
  • 已假定长期人口。

然后您可以在单元格 C1 中输入公式 ="insertCity(new ObjectCity("&CHAR(34)&A1&CHAR(34)&","&B1&"L));"。然后您可以将此单元格复制到 c2-c1300(使用上面的电子表格的 c2-c17)。生成的电子表格如下:-

然后您可以将生成的代码(单元格 c1-c1300)复制并粘贴到 suitable 位置。

这是一个工作示例:-

ObjectCityclass:-

public class ObjectCity {

    private String cityName;
    private Long cityPopulation;

    public ObjectCity(String cityName, Long cityPopulation) {
        this.cityName = cityName;
        this.cityPopulation = cityPopulation;
    }

    public String getCityName() {
        return cityName;
    }

    public Long getCityPopulation() {
        return cityPopulation;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public void setCityPopulation(Long cityPopulation) {
        this.cityPopulation = cityPopulation;
    }
}

DatabaseHelper DBHelper class(基于问题中的代码):-

public class DBHelper extends SQLiteOpenHelper {

    public static final String MI_TABLA_CITIES = "city";

    public DBHelper(Context context) {
        super(context, "theDatabase", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String crearTablaCities = "CREATE TABLE "+MI_TABLA_CITIES+" (ID_CITY INTEGER PRIMARY KEY AUTOINCREMENT, NAME_CITY TEXT, POPULATION_CITY INTEGER)";
        db.execSQL(crearTablaCities);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {

    }

    public void insertCity(ObjectCity newCity){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        //cv.put("ID_CITY", newCity.getCityID());
        cv.put("NAME_CITY", newCity.getCityName());
        cv.put("POPULATION_CITY", newCity.getCityPopulation());
        db.insert(MI_TABLA_CITIES,null,cv);
        //db.close();

    }

    /* function to load the country data */
    public void loadData() {
        if(DatabaseUtils.queryNumEntries(this.getWritableDatabase(),MI_TABLA_CITIES)> 0) return;

        insertCity(new ObjectCity("Tokyo",37339804L));
        insertCity(new ObjectCity("Delhi",31181376L));
        insertCity(new ObjectCity("Shanghai",27795702L));
        insertCity(new ObjectCity("Sao Paulo",22237472L));
        insertCity(new ObjectCity("Mexico City",21918936L));
        insertCity(new ObjectCity("Dhaka",21741090L));
        insertCity(new ObjectCity("Cairo",21322750L));
        insertCity(new ObjectCity("Beijing",20896820L));
        insertCity(new ObjectCity("Mumbai",20667656L));
        insertCity(new ObjectCity("Osaka",19110616L));
        insertCity(new ObjectCity("Karachi",16459472L));
        insertCity(new ObjectCity("Chongqing",16382376L));
        insertCity(new ObjectCity("Istanbul",15415197L));
        insertCity(new ObjectCity("Buenos Aires",15257673L));
        insertCity(new ObjectCity("Kolkata",14974073L));
        insertCity(new ObjectCity("Kinshasa",14970460L));
        insertCity(new ObjectCity("Lagos",14862111L));
    }
}
  • 注意loadData方法。

    • 这使用 DatabaseUtils queryNumEntries 方法检查是否存在任何数据,并且仅在 table.
    • 中没有行时才加载数据
    • 其余代码是从上面的电子表格中复制并粘贴的(第二张图片)。

最后一次调用 activity MainActivity :-

public class MainActivity extends AppCompatActivity {

    DBHelper db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = new DBHelper(this);
        db.loadData(); //<<<<< LOADS THE CITY DATA (if not already loaded)
    }
}

结果

运行 以上并使用 Android Studio 的数据库检查器显示:-

从第一个回答开始:-

c) Save the data as a csv and use an SQLite tool to import and load the data and to then copy that database as an asset and then use that database.

然后使用 Excel 保存了原始 sheet 的 csv。这是导入到 SQLite 的 SQLite 工具 Navicat for SQLite(还有其他这样的工具,但我更喜欢 Navicat):-

数据库和连接已关闭(保存数据库)。

在 Android studio 中,AppAndroid View 和 [=34= 中被右键单击]New 然后选择(单击)Directory 并从对话框中选择 src/Android/assets (也就是在 app/src/main 中创建资产文件夹(可以是在 Android Studio 之外完成)。

数据库文件(名为 thedatabase.db)已复制到新创建的资产文件夹中。

数据库助手 class DBHelperB 按照 :-

编写
public class DBHelperB extends SQLiteOpenHelper {


    /*
        Note database created in SQLite tool and data imported from spreadsheet
        database file is the copied into the assets folder (after creating the folder)
     */
    public static final String DBNAME = "thedatabase.db"; //<<<< asset file name must match
    public static final String MI_TABLA_CITIES = "city";

    private static volatile DBHelperB instance = null;

    // Prevent construction outside
    private DBHelperB(Context context) {
        super(context, "theDatabase", null, 1);
    }

    // instead of using db = new DBHelper(this); 
    // this allows db = DBHelperB.getInstance(); 
    // i.e. a single instance (aka a singleton) is retrieved
    // IMPORTANTLY this also copies the asset DB if not already loaded 
    public static DBHelperB getDBInstance(Context context) {
        if (instance == null) {
            getAssetDB(context); // <<<<< Copies ASSET DB
            instance = new DBHelperB(context);
        }
        return instance;
    }

    /* Won't be called as the DB will exists */
    @Override
    public void onCreate(SQLiteDatabase db) {
        String crearTablaCities = "CREATE TABLE "+MI_TABLA_CITIES+" (ID_CITY INTEGER PRIMARY KEY AUTOINCREMENT, NAME_CITY TEXT, POPULATION_CITY INTEGER)";
        db.execSQL(crearTablaCities);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {

    }

    public void insertCity(ObjectCity newCity){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        //cv.put("ID_CITY", newCity.getCityID());
        cv.put("NAME_CITY", newCity.getCityName());
        cv.put("POPULATION_CITY", newCity.getCityPopulation());
        db.insert(MI_TABLA_CITIES,null,cv);
        //db.close();

    }

    /* 
        Copies the DB from the assets folder unless the db already exists
        Note if this fails a runtime exception will occur. It is then
        IMPORTANT to look at the log to determine the cause
        More often than not a failure is due to the asset not having been copied correctly
    
     */
    private static void getAssetDB(Context context) {
        File dbFile = context.getDatabasePath(DBNAME);
        InputStream asset;
        OutputStream db;
        byte[] buffer = new byte[4096];
        if (dbFile.exists()) return; // Database exists so no need to copy
        /* Ensure that the data/data/<package_name>/databases folder exists */
        if (!dbFile.getParentFile().exists()) {
            dbFile.getParentFile().mkdirs();
        }
        try {
            asset = context.getAssets().open(DBNAME);
            db = new FileOutputStream(dbFile);
            int length;
            while ((length = asset.read(buffer)) > 0) {
                db.write(buffer,0,length);
            }
            db.flush();
            db.close();
            asset.close();

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to copy asset file");
        }
    }
}

MainActivity 被修改为:-

public class MainActivity extends AppCompatActivity {

    DBHelper db;
    DBHelperB assetdb; //ADDED

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = new DBHelper(this);
        db.loadData();
        // ADDED >
        assetdb = DBHelperB.getDBInstance(this); /* will copy the asset db if need be */
        /* Database inspector doesn't like this data so show data another way */
        Cursor csr = assetdb.getWritableDatabase().query("city",null,null,null,null,null,null);
        DatabaseUtils.dumpCursor(csr);
    }
}
  • 查看评论

结果,在 运行 之后,根据日志包括:-

2021-07-15 09:16:54.454 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@374559d
2021-07-15 09:16:54.455 I/System.out: 0 {
2021-07-15 09:16:54.455 I/System.out:    ID_CITY=1
2021-07-15 09:16:54.455 I/System.out:    NAME_CITY=Tokyo
2021-07-15 09:16:54.455 I/System.out:    POPULATION_CITY=37339804
2021-07-15 09:16:54.455 I/System.out: }
2021-07-15 09:16:54.455 I/System.out: 1 {
2021-07-15 09:16:54.456 I/System.out:    ID_CITY=2
2021-07-15 09:16:54.456 I/System.out:    NAME_CITY=Delhi
2021-07-15 09:16:54.456 I/System.out:    POPULATION_CITY=31181376
2021-07-15 09:16:54.456 I/System.out: }
2021-07-15 09:16:54.456 I/System.out: 2 {
2021-07-15 09:16:54.456 I/System.out:    ID_CITY=3
2021-07-15 09:16:54.456 I/System.out:    NAME_CITY=Shanghai
2021-07-15 09:16:54.456 I/System.out:    POPULATION_CITY=27795702
2021-07-15 09:16:54.456 I/System.out: }
....