【问题标题】:How to add 1300 rows to SQLite table?如何向 SQLite 表添加 1300 行?
【发布时间】:2021-09-23 13:57:38
【问题描述】:

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

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

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

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();
    }

我不知道如何面对下一步。有人可以给我一些提示以找到方法吗?提前非常感谢

【问题讨论】:

    标签: android sqlite android-studio android-sqlite


    【解决方案1】:

    您可以通过 3 种相对简单的方法来完成此操作。

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

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

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

    选项A很简单,假设你有类似的东西:-

    您的代码显示您有一个 insertCity 方法,该方法采用 City 对象。假设您使用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)拖放复制并粘贴到合适的位置。

    这是一个工作示例:-

    ObjectCity 类:-

    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 类(基于问题中的代码):-

    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 方法来检查是否存在任何数据,并且仅当表中没有行时才加载数据。
      • 其余代码是从上面的电子表格中复制和粘贴的(第二张图片)。

    最后一个调用活动 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 的 Database Inspector 显示:-

    【讨论】:

      【解决方案2】:

      从第一个答案开始:-

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

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

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

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

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

      Database Helper 类 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);
          }
      }
      
      • 见 cmets

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

      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: }
      ....
      

      【讨论】:

      • 惊人的答案!解释得很好,很完整,很有用!它对我有很大帮助!非常感谢!!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-25
      • 2021-10-07
      • 1970-01-01
      • 2021-04-23
      • 2017-09-04
      • 1970-01-01
      相关资源
      最近更新 更多