创建多个表并将数据插入其中 [英] Creating multiple Tables and inserting Data into them

查看:240
本文介绍了创建多个表并将数据插入其中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的应用程序,我需要在数据库中创建2个不同的表,但我的问题是始终只创建一个表.

For my application I need to create 2 different tables in my database, my problem is that there is always only one table created.

这是DatabaseHelper类的核心:-

This is the core of the DatabaseHelper class:-

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "Stundenplan.db";
    public static final String TABLE_NAME = "Fach_table";
    public static final String FACH_ID = "ID";
    public static final String FACH_NAME = "FACHNAME";
    public static final String FACH_KUERZEL = "FACHKUERZEL";
    public static final String FACH_RAUM = "FACHRAUM";
    public static final String FACH_LEHRER = "FACHLEHRER";
    public static final String FACH_FARBE = "FACHFARBE";
    public static final String TABLE_LEHRER = "Lehrer_table";
    public static final String LEHRERID = "ID_L";
    public static final String LEHRERNAME = "LEHRERNAME";
    public static final String LEHRERKUERZEL = "LEHRERKUERZEL";
    public static final String LEHRERRAUM = "LEHRERRAUM";
    public static final String LEHRERMAIL = "LEHRERMAIL";

    private static final String create_Table2 = "create table " + TABLE_LEHRER + "("+ LEHRERID +"INTEGER PRIMARY KEY," + LEHRERNAME +"TEXT," + LEHRERKUERZEL + "TEXT,"+ LEHRERRAUM + "TEXT," + LEHRERMAIL + "TEXT)";
    private static final String create_Table =  "create table " + TABLE_NAME + "("+ FACH_ID + "INTEGER PRIMARY KEY," + FACH_NAME +"TEXT," + FACH_KUERZEL + " TEXT,"+ FACH_RAUM + "TEXT," + FACH_LEHRER + " TEXT)";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);

        Log.d("MeineAPP", "DB angelegt");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        Log.d("MeineAPP", "Tabelle angelegt");
        //  db.execSQL("create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, FACHNAME TEXT, FACHKUERZEL TEXT, FACHRAUM TEXT, FACHLEHRER TEXT)");
        db.execSQL(create_Table);
        db.execSQL(create_Table2);

    }

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

        // db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME );
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        db.execSQL( "DROP TABLE IF EXISTS " + TABLE_LEHRER);

        onCreate(db);
        Log.d("MeineAPP", "in upgrade");

    }
...........   
}

请帮助!

推荐答案

您的问题总是只创建一个表",这是由于对 onCreate 方法的一种非常普遍的误解. ,每次运行该应用程序时,都会在 DatabaseHelper.java (通常称为数据库帮助器)中运行.实际上,在数据库的整个生命周期中,onCreate方法仅自动调用一次.

Your issue "there is always only one table created", will be due to the very common misconception that the onCreate method, in DatabaseHelper.java (generally termed the Database Helper) runs every time the App is run. Actually the onCreate method is only automatically invoked once for the lifetime of the database.

如果保存在数据库中的数据可能丢失,那么解决方法很简单,那就是删除数据库.

If the data held in the database can be lost then the fix is simply, delete the database.

  • 这可以通过以下任一方式完成
    • 从设置/应用中删除应用的数据,或
    • 从设置/应用程序卸载应用程序 然后重新运行该应用程序时,将调用onCreate方法.
    • this can be done by either
      • deleting the App's data from settings/Apps or
      • uninstalling the App from settings/Apps When the App is then rerun the onCreate method will then be invoked.

      根据您的情况,onUpgrade会删除表(如果存在),然后调用onCreate方法.作为删除应用程序数据/卸载应用程序的一种替代方法,是增加数据库版本,这将导致onUpgrade方法运行,从而重新创建表.

      In your situation the onUpgrade drops the tables, if they exist, and then invokes the onCreate method. As such an alternative to deleting the App's data/uninstalling the App, would be to increase the Database Version, which will then cause the onUpgrade method to be run, and thus recreating the tables.

      注意,这仍然会导致所有现有数据丢失.

      Note this would still result in any existing data being lost.

      例如:-

      public DatabaseHelper(Context context) {
          super(context, DATABASE_NAME, null, 2); //<<<< CHANGED 1 to 2
          Log.d("MeineAPP", "DB angelegt");
      }
      

      代码测试

      实际的表创建语句可以正常工作,并使用 logDatabaseInfo 干净地生成:-

      Testing of your code

      The actual table create statements work and using logDatabaseInfo from this a clean run produces :-

      05-26 20:52:24.618 1398-1398/? D/MeineAPP: DB angelegt
      05-26 20:52:24.622 1398-1398/? D/SQLITE_CSU: DatabaseList Row 1 Name=main File=/data/data/jannikokan.de.stundenplan/databases/Stundenplan.db
          Database Version = 1
          Table Name = android_metadata Created Using = CREATE TABLE android_metadata (locale TEXT)
      05-26 20:52:24.626 1398-1398/? D/SQLITE_CSU: Table = android_metadata ColumnName = locale ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
          Table Name = Fach_table Created Using = CREATE TABLE Fach_table(IDINTEGER PRIMARY KEY,FACHNAMETEXT,FACHKUERZEL TEXT,FACHRAUMTEXT,FACHLEHRER TEXT)
          Table = Fach_table ColumnName = IDINTEGER ColumnType =  Default Value = null PRIMARY KEY SEQUENCE = 1
          Table = Fach_table ColumnName = FACHNAMETEXT ColumnType =  Default Value = null PRIMARY KEY SEQUENCE = 0
          Table = Fach_table ColumnName = FACHKUERZEL ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
          Table = Fach_table ColumnName = FACHRAUMTEXT ColumnType =  Default Value = null PRIMARY KEY SEQUENCE = 0
          Table = Fach_table ColumnName = FACHLEHRER ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
          Table Name = Lehrer_table Created Using = CREATE TABLE Lehrer_table(ID_LINTEGER PRIMARY KEY,LEHRERNAMETEXT,LEHRERKUERZELTEXT,LEHRERRAUMTEXT,LEHRERMAILTEXT)
          Table = Lehrer_table ColumnName = ID_LINTEGER ColumnType =  Default Value = null PRIMARY KEY SEQUENCE = 1
          Table = Lehrer_table ColumnName = LEHRERNAMETEXT ColumnType =  Default Value = null PRIMARY KEY SEQUENCE = 0
          Table = Lehrer_table ColumnName = LEHRERKUERZELTEXT ColumnType =  Default Value = null PRIMARY KEY SEQUENCE = 0
          Table = Lehrer_table ColumnName = LEHRERRAUMTEXT ColumnType =  Default Value = null PRIMARY KEY SEQUENCE = 0
          Table = Lehrer_table ColumnName = LEHRERMAILTEXT ColumnType =  Default Value = null PRIMARY KEY SEQUENCE = 0
      

      但是,在查看代码时,您确实遇到了两个方法(zeigeFaecherzeigeLehrer)的问题,因为您省略了 * ,即您有 *from ,应该为 * from .

      However, looking at your code you do have an issue with two methods (zeigeFaecher and zeigeLehrer) in that you have omitted a space between * and from i.e. you have *from which should be * from.

      • 注意测试仅限于此问题,测试绝不是说没有其他方面会或不会导致问题.
      • Note testing was limited to this issue specifically and that the testing is by no means saying that there are not other aspects that will or will not result in issues.

      如果需要保留数据,则必须设计一种保存数据的方法.

      If you have data that needs to be kept then you will have to devise a method of keeping the data.

      就像添加一个检查以查看期望的表是否存在以及是否不创建期望表一样简单.您可以在Databasehelper.java中添加以下内容:-

      It could be as simple as adding a check to see if the expected tables exist and if not to create them e.g. you could have/add the following in Databasehelper.java :-

      例如:-

      // This is the publicly accessible driver that has the core lists
      // i.e. the list of tables that should exist and the
      // corresponding table create statements which are passed to
      // the createTablesThatDoNotExist method
      public void addAnyNewTables() {
          String[] required_tables = new String[]{
                  TABLE_NAME,
                  TABLE_LEHRER
          };
      
          String[] table_create_statements = new String[] {
            create_Table,
            create_Table2
          };
          createTablesThatDoNotExist(required_tables,table_create_statements);
      }
      
      
      // This method checks the validity lengths and count of the 2 arrays
      // loping through them if valid pass the table and the create statement to the
      // doCheckAndCreateOfTable method.
      private void createTablesThatDoNotExist(String[] required_tables, String[] table_create_statements) {
      
          // If no tables or table create statements then finish
          if (required_tables.length < 1 || table_create_statements.length < 1) {
              return;
          }
          // elements in arrays must match
          if (required_tables.length != table_create_statements.length) {
              return;
          }
          SQLiteDatabase db = this.getWritableDatabase();
          String whereclause = "name";
          for (int i=0; i < required_tables.length;i++) {
              if (required_tables[i].length() > 0 && table_create_statements[i].length() > 0) {
                  doCheckAndCreateOfTable(
                          required_tables[i].toString(),
                          table_create_statements[i].toString()
                  );
              }
          }
      }
      
      // This does the real work by interrogatin sqlite_master to see if the table
      // exists. If not then it runs the query to create the table using the
      // create_statement passed.
      private void doCheckAndCreateOfTable(String table,String create_statement) {
          SQLiteDatabase db = this.getWritableDatabase();
          String whereclause = "name=? AND type=?";
          String[] whereargs = new String[]{table,"table"};
          String table_to_query = "sqlite_master";
          Cursor csr = db.query(table_to_query,null,whereclause,whereargs,null,null,null);
          if (csr.getCount() < 1) {
              db.execSQL(create_statement);
          }
          csr.close();
      }
      

      您可以在获取DatabaseHelper实例后,在初始活动中调用它,例如:-

      You could then invoke this in the initial activity after getting an instance of the DatabaseHelper e.g. :-

          mDBHlpr = new DatabaseHelper(this);
          mDBHlpr.addAnyNewTables();
          SQLiteDatabase db = mDBHlpr.getWritableDatabase();
          CommonSQLiteUtilities.logDatabaseInfo(db);
      

      通过对第二个表的创建进行注释,删除应用程序的数据(并因此删除数据库),然后在onCreate中使用以下命令运行应用程序(有意不创建第二个表),对上述内容进行了测试

      The above was tested by commenting out the creation of the second table, deleting the App's data (and therefore the database) and then running the App using the following in the onCreate (to purposefully NOT create the 2nd table)

      public void onCreate(SQLiteDatabase db) {
      
          Log.d("MeineAPP", "Tabelle angelegt");
          //  db.execSQL("create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, FACHNAME TEXT, FACHKUERZEL TEXT, FACHRAUM TEXT, FACHLEHRER TEXT)");
          db.execSQL(create_Table);
          //db.execSQL(create_Table2); //<<<< COMMENTED OUT FOR TEST
      
      }
      

      结果输出为:-

      05-26 21:16:07.672 1742-1742/? D/MeineAPP: DB angelegt
      05-26 21:16:07.672 1742-1744/? D/dalvikvm: GC_CONCURRENT freed 236K, 10% free 6158K/6791K, paused 11ms+0ms, total 15ms
      05-26 21:16:07.708 1742-1742/? D/SQLITE_CSU: DatabaseList Row 1 Name=main File=/data/data/jannikokan.de.stundenplan/databases/Stundenplan.db
          Database Version = 1
          Table Name = android_metadata Created Using = CREATE TABLE android_metadata (locale TEXT)
          Table = android_metadata ColumnName = locale ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
          Table Name = Fach_table Created Using = CREATE TABLE Fach_table(IDINTEGER PRIMARY KEY,FACHNAMETEXT,FACHKUERZEL TEXT,FACHRAUMTEXT,FACHLEHRER TEXT)
          Table = Fach_table ColumnName = IDINTEGER ColumnType =  Default Value = null PRIMARY KEY SEQUENCE = 1
          Table = Fach_table ColumnName = FACHNAMETEXT ColumnType =  Default Value = null PRIMARY KEY SEQUENCE = 0
          Table = Fach_table ColumnName = FACHKUERZEL ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
          Table = Fach_table ColumnName = FACHRAUMTEXT ColumnType =  Default Value = null PRIMARY KEY SEQUENCE = 0
          Table = Fach_table ColumnName = FACHLEHRER ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
          Table Name = Lehrer_table Created Using = CREATE TABLE Lehrer_table(ID_LINTEGER PRIMARY KEY,LEHRERNAMETEXT,LEHRERKUERZELTEXT,LEHRERRAUMTEXT,LEHRERMAILTEXT)
          Table = Lehrer_table ColumnName = ID_LINTEGER ColumnType =  Default Value = null PRIMARY KEY SEQUENCE = 1
          Table = Lehrer_table ColumnName = LEHRERNAMETEXT ColumnType =  Default Value = null PRIMARY KEY SEQUENCE = 0
          Table = Lehrer_table ColumnName = LEHRERKUERZELTEXT ColumnType =  Default Value = null PRIMARY KEY SEQUENCE = 0
          Table = Lehrer_table ColumnName = LEHRERRAUMTEXT ColumnType =  Default Value = null PRIMARY KEY SEQUENCE = 0
          Table = Lehrer_table ColumnName = LEHRERMAILTEXT ColumnType =  Default Value = null PRIMARY KEY SEQUENCE = 0
      

      即这两个表都已创建

      这篇关于创建多个表并将数据插入其中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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