SQLite,启动时仅读取只修改一个 table 但不修改第二个

SQLite, when launched only reads only modifies one table but not the second one

我正在尝试编码两个 table。

一个保存一些鞋子的信息,另一个保存品牌的信息。

虽然这双鞋一只很好用,但另一只却不行。

public class AdminSQLiteOpenHelper extends SQLiteOpenHelper {
    public AdminSQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql1 = "create table zaps(matricula text primary key,color text,talla text)";
        String sql2 = "create table alumnos(matricula text primary key,nombre text,tel text)";
        Log.d("Data", "onCreate: " + sql1);
        Log.d("Data", "onCreate: " + sql2);
        db.execSQL(sql1);
        db.execSQL(sql2);
    }

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

    }
}

这是我要修改 table 的品牌的 activity。

public class ProvActivity extends AppCompatActivity {
    EditText etMatricula, etNombre, etTel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prov);
        etMatricula = (EditText) findViewById(R.id.etMatricula);
        etNombre = (EditText) findViewById(R.id.etNombre);
        etTel = (EditText) findViewById(R.id.etTel);

    }

    public void guardar(View v) {
        try {
            AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this,
                    "administracion1", null, 1);
            SQLiteDatabase bd1 = admin.getWritableDatabase();
            ContentValues reg = new ContentValues();
            reg.put("matricula", etMatricula.getText().toString());
            reg.put("nombre", etNombre.getText().toString());
            reg.put("tel", etTel.getText().toString());
            bd1.insert("alumnos", null, reg);
            bd1.close();
            etMatricula.setText("");
            etNombre.setText("");
            etTel.setText("");
            etMatricula.requestFocus();
            Toast.makeText(this, "Se ha guardado el registro con éxito.",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT);
        }
    }

    public void consultar_matricula(View v) {
        try {
            AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this,
                    "administracion1", null, 1);
            SQLiteDatabase bd1 = admin.getWritableDatabase();
            String cod = etMatricula.getText().toString();
            Cursor fila = bd1.rawQuery(
                    "select nombre,tel from alumnos where matricula=" + cod, null);
            if (fila.moveToFirst()) {
                etNombre.setText(fila.getString(0));
                etTel.setText(fila.getString(1));
            } else
                Toast.makeText(this, "No existe un registro con dicha matrícula.",
                        Toast.LENGTH_SHORT).show();
            bd1.close();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT);
        }

    }
}

您展示的代码可以将数据插入数据库。

因此,您可能遇到以下常见问题之一。

您已将另一个 table 添加到 AdminSQLiteOpenHelper class 的 onCreate 方法中的代码中,因为 运行 应用程序

  • 数据库助手(class 扩展 SQLiteOpenHelper)的 onCreate 方法在数据库的生命周期内仅 运行 一次。
  • 要更改架构(例如添加 table),您必须在其他地方应用更改(例如通过 onUpgrade 方法,同时增加数据库版本)或者,开发App的时候经常会这样,删除数据库。您可以通过以下任一方式轻松删除数据库:-

    • 卸载应用程序,或
    • 正在删除应用程序的数据。

错误判断缺少数据

  • 这通常是由于试图通过 GUI 确定数据的存在,但没有刷新显示的数据造成的。

测试

以下代码用于测试该代码在向数据库添加数据方面确实有效。

AdminSQLiteOpenHelper.java

public class AdminSQLiteOpenHelper extends SQLiteOpenHelper {

    public AdminSQLiteOpenHelper(@Nullable Context context) {
        super(context, "administracion1", null, 1);
    }

    /*
        See above for easier to use constructor (just pass the Context)
     */
    public AdminSQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql1 = "create table zaps(matricula text primary key,color text,talla text)";
        String sql2 = "create table alumnos(matricula text primary key,nombre text,tel text)";
        Log.d("Data", "onCreate: " + sql1);
        Log.d("Data", "onCreate: " + sql2);
        db.execSQL(sql1);
        db.execSQL(sql2);
    }

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

    }

    /*
        Added to simplify testing
     */
    public long insertAlumnos(String matricula, String nombre, String tel) {
        ContentValues cv = new ContentValues();
        cv.put("matricula",matricula);
        cv.put("nombre",nombre);
        cv.put("tel",tel);
        SQLiteDatabase db = this.getWritableDatabase();
        return db.insert("alumnos",null,cv);
    }

    public long insertZaps(String matricula, String color, String talla) {
        ContentValues cv = new ContentValues();
        cv.put("matricula",matricula);
        cv.put("color",color);
        cv.put("talla",talla);
        SQLiteDatabase db = this.getWritableDatabase();
        return db.insert("zaps",null,cv);
    }

    public void logAllZaps() {
        logAllRows("zaps");
    }

    public void logAllAlumnos() {
        logAllRows("alumnos");
    }

    private void logAllRows(String table) {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor csr = db.query(table,null,null,null,null,null,null);
        DatabaseUtils.dumpCursor(csr);
        csr.close();
    }
}
  • 请注意,additions/changes 是在初步检查代码后创建的。这些更改只是让事情更容易明智地进行测试。

MainActivity.java

这只是一个简化的 activity,它使用原始数据而不是通过 UI 获取数据:-

public class MainActivity extends AppCompatActivity {
    AdminSQLiteOpenHelper adminHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        adminHelper = new AdminSQLiteOpenHelper(this);
        adminHelper.insertZaps("test","red","blah");
        adminHelper.insertAlumnos("test","199","0000000000");
        adminHelper.logAllZaps();
        adminHelper.logAllAlumnos();
        //guardar();
        //other();
    }

    /* Not USED although tested */
    public void guardar() {
            AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this,
                    "administracion1", null, 1);
            SQLiteDatabase bd1 = admin.getWritableDatabase();
            ContentValues reg = new ContentValues();
            reg.put("matricula", "test");
            reg.put("nombre", "100");
            reg.put("tel", "0000000000");
            bd1.insert("alumnos", null, reg);
            //bd1.close();
    }
}

初始运行结果:-

2019-11-28 13:11:29.348 4788-4788/a.so59080227 D/Data: onCreate: create table zaps(matricula text primary key,color text,talla text)
2019-11-28 13:11:29.348 4788-4788/a.so59080227 D/Data: onCreate: create table alumnos(matricula text primary key,nombre text,tel text)
2019-11-28 13:11:29.368 4788-4788/a.so59080227 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@5df21a1
2019-11-28 13:11:29.371 4788-4788/a.so59080227 I/System.out: 0 {
2019-11-28 13:11:29.372 4788-4788/a.so59080227 I/System.out:    matricula=test
2019-11-28 13:11:29.372 4788-4788/a.so59080227 I/System.out:    color=red
2019-11-28 13:11:29.372 4788-4788/a.so59080227 I/System.out:    talla=blah
2019-11-28 13:11:29.372 4788-4788/a.so59080227 I/System.out: }
2019-11-28 13:11:29.372 4788-4788/a.so59080227 I/System.out: <<<<<
2019-11-28 13:11:29.372 4788-4788/a.so59080227 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@fc68fc6
2019-11-28 13:11:29.373 4788-4788/a.so59080227 I/System.out: 0 {
2019-11-28 13:11:29.373 4788-4788/a.so59080227 I/System.out:    matricula=test
2019-11-28 13:11:29.373 4788-4788/a.so59080227 I/System.out:    nombre=199
2019-11-28 13:11:29.373 4788-4788/a.so59080227 I/System.out:    tel=0000000000
2019-11-28 13:11:29.373 4788-4788/a.so59080227 I/System.out: }
2019-11-28 13:11:29.373 4788-4788/a.so59080227 I/System.out: <<<<<
  • 如您所见,两个 table 都已创建,添加的数据已转储到日志中。

你只需要像下面这样使用 SQLiteOpenHelper 的 onUpgrade 方法。可能是您的第二个 table 目前没有创建。 因此,对于通用解决方案,您需要增加数据库版本(AdminSQLiteOpenHelper 构造函数的第 4 个字段)并添加以下代码而不是 onUpgrade 方法。

public class AdminSQLiteOpenHelper extends SQLiteOpenHelper {
public AdminSQLiteOpenHelper(@Nullable Context context, @Nullable String 
name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
}


@Override
public void onCreate(SQLiteDatabase db) {
    String sql1 = "create table if not exists zaps(matricula text primary 
key,color text,talla text)";
    String sql2 = "create table if not exists alumnos(matricula text primary 
key,nombre text,tel text)";
    Log.d("Data", "onCreate: " + sql1);
    Log.d("Data", "onCreate: " + sql2);
    db.execSQL(sql1);
    db.execSQL(sql2);
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
  String sql1 = "create table if not exists zaps(matricula text primary 
key,color text,talla text)";
    String sql2 = "create table if not exists alumnos(matricula text primary 
key,nombre text,tel text)";
    Log.d("Data", "onCreate: " + sql1);
    Log.d("Data", "onCreate: " + sql2);
    db.execSQL(sql1);
    db.execSQL(sql2);
}
}