SQLite创建一个表后未创建另一个表

时间:2019-06-06 06:59:50

标签: java android android-sqlite

我正在创建一个包含各种表的数据库,所以现在我有了一个“ Admin”表,我试图添加一个“ Client”表,但是当我初始化“ Admin”表时,“ Client”表却没有创建并反之亦然...

我尝试在一个活动中创建“ Admin”表,在另一个活动中创建“ Client”表,但结果相同,即创建的表是第一个被调用的表

创建“管理员”表并尝试向“客户端”表中添加一些数据时,我没有任何错误,但是当我尝试从“客户端”表中获取数据时,出现了错误:

android.database.sqlite.SQLiteException:否这样的表:client_list(代码1):,而编译时:SELECT * FROM client_list  错误代码:1(SQLITE_ERROR)     原因:SQL(查询)错误或数据库丢失。

     //This is my DatabaseHelper

     public class DatabaseHelper extends SQLiteOpenHelper {


    private static final String DATABASE_NAME = "Users.db";
    private static final int VERSION = 1;
    private static int SELECTION;



    public DatabaseHelper(Context context, int SELECTION){
        super(context, DATABASE_NAME, null, VERSION);
        this.SELECTION = SELECTION;
    }

    @Override
    public void onCreate(SQLiteDatabase _db) {

        switch (SELECTION){

            case 1:
                // Iniciamos la tabla de admins a guardar
                _db.execSQL(initAdminTable());

                break;
            case 2:
                // Iniciamos la tabla de clientes a guardar
                _db.execSQL(initClientTable());
                break;
        }

    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        switch(SELECTION){
            case 1:
                db.execSQL("DROP TABLE IF EXISTS "+ AdminContract.TABLE_NAME);
                onCreate(db);
                break;
            case 2:
                db.execSQL("DROP TABLE IF EXISTS "+ ClientContract.TABLE_NAME);
                onCreate(db);
                break;
        }

    }


    private String initClientTable(){

        final String SQL_CREATE_CLIENTLIST_TABLE = " CREATE TABLE IF NOT EXISTS " +
                ClientContract.TABLE_NAME + " (" +
                ClientContract._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
                ClientContract.NOMBRE_CLIENTE + " TEXT NOT NULL, " +
                ClientContract.NOMBRE_LOCAL + " TEXT NOT NULL, "+
                ClientContract.DIRECCION + " TEXT NOT NULL, " +
                ClientContract.CIUDAD + " TEXT NOT NULL, " +
                ClientContract.CORREO + " TEXT NOT NULL, "+
                ClientContract.ZONA + " TEXT NOT NULL, "+
                ClientContract.NUMERO_TELEFONO + " INTEGER NOT NULL, " +
                ClientContract.CODIGO_VENDEDOR + " INTEGER NOT NULL, " +
                ClientContract.RUC + " INTEGER NOT NULL, " +
                ClientContract.STANDBY + " INTEGER NOT NULL, " + // 0 Inactivo, 1 Activo
                ClientContract.TIME_STAMP + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP );";

        return SQL_CREATE_CLIENTLIST_TABLE;
    }

    private String initAdminTable(){

        final String SQL_CREATE_ADMINLIST_TABLE = " CREATE TABLE IF NOT EXISTS " +
                AdminContract.TABLE_NAME + " (" +
                AdminContract._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
                AdminContract.NOMBRE + " TEXT NOT NULL, " +
                AdminContract.DIRECCION_DOMICILIO + " TEXT NOT NULL, " +
                AdminContract.CIUDAD + " TEXT NOT NULL, " +
                AdminContract.CORREO + " TEXT NOT NULL, "+
                AdminContract.PASSWORD + " TEXT NOT NULL, "+
                AdminContract.NUMERO_TELEFONO + " INTEGER NOT NULL, " +
                AdminContract.RUC + " INTEGER NOT NULL, " +
                AdminContract.TIME_STAMP + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP );";

        return SQL_CREATE_ADMINLIST_TABLE;
    }


    // ADMIN METHODS -------------------------------------------------------------------------------
    public void addAdmin(Admin admin){
        if(SELECTION == 1){
            SQLiteDatabase database = this.getWritableDatabase();
            ContentValues cv = new ContentValues();
            // Iniciamos datos
            cv.put(AdminContract.NOMBRE, admin.getNombre());
            cv.put(AdminContract.CIUDAD, admin.getCiudad());
            cv.put(AdminContract.CORREO, admin.getCorreo());
            cv.put(AdminContract.PASSWORD, admin.getPassword());
            cv.put(AdminContract.DIRECCION_DOMICILIO, admin.getDireccionDomicilio());
            cv.put(AdminContract.NUMERO_TELEFONO, admin.getNumeroTelefono());
            cv.put(AdminContract.RUC, admin.getRUC());
            // Insertamos
            database.insert(AdminContract.TABLE_NAME, null, cv);
            database.close();
        }

    }

    public Admin getAdminById(int id){

        if(SELECTION == 1) {
            SQLiteDatabase database = this.getReadableDatabase();
            Cursor cursor = database.query(AdminContract.TABLE_NAME, AdminContract.COLUMNS, "_id = ?", new String[]{String.valueOf(id)}, null, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
            }

            Admin admin = new Admin();
            admin.setNombre(cursor.getString(cursor.getColumnIndex(AdminContract.NOMBRE)));
            admin.setDireccionDomicilio(cursor.getString(cursor.getColumnIndex(AdminContract.DIRECCION_DOMICILIO)));
            admin.setCiudad(cursor.getString(cursor.getColumnIndex(AdminContract.CIUDAD)));
            admin.setCorreo(cursor.getString(cursor.getColumnIndex(AdminContract.CORREO)));
            admin.setPassword(cursor.getString(cursor.getColumnIndex(AdminContract.PASSWORD)));
            admin.setNumeroTelefono(cursor.getString(cursor.getColumnIndex(AdminContract.NUMERO_TELEFONO)));
            admin.setRUC(cursor.getString(cursor.getColumnIndex(AdminContract.RUC)));

            cursor.close();
            return admin;
        }else{
            return null;
        }
    }

    public int getAdminCursorCount(){
        SQLiteDatabase database = this.getReadableDatabase();
        String query = "SELECT * FROM " + AdminContract.TABLE_NAME;
        Cursor cursor = database.rawQuery(query, null);

        return  cursor.getCount();
    }

    public List<Admin> getAllAdmins(){

        if(SELECTION == 1) {
            List<Admin> adminList = new List<Admin>();
            SQLiteDatabase database = this.getWritableDatabase();
            String query = "SELECT * FROM " + AdminContract.TABLE_NAME;
            Cursor cursor = database.rawQuery(query, null);

            Admin admin = null;
            if (cursor.moveToFirst()) {
                do {
                    admin = new Admin();
                    admin.setNombre(cursor.getString(cursor.getColumnIndex(AdminContract.NOMBRE)));
                    admin.setDireccionDomicilio(cursor.getString(cursor.getColumnIndex(AdminContract.DIRECCION_DOMICILIO)));
                    admin.setCiudad(cursor.getString(cursor.getColumnIndex(AdminContract.CIUDAD)));
                    admin.setCorreo(cursor.getString(cursor.getColumnIndex(AdminContract.CORREO)));
                    admin.setPassword(cursor.getString(cursor.getColumnIndex(AdminContract.PASSWORD)));
                    admin.setNumeroTelefono(cursor.getString(cursor.getColumnIndex(AdminContract.NUMERO_TELEFONO)));
                    admin.setRUC(cursor.getString(cursor.getColumnIndex(AdminContract.RUC)));

                    adminList.addTop(admin);
                } while (cursor.moveToNext());
            }

            cursor.close();
            return adminList;
        }else{
            return null;
        }

    }
    // END OF ADMIN METHODS ------------------------------------------------------------------------

    // CLIENT METHODS ------------------------------------------------------------------------------
    public void addClient(Cliente cliente){
        if(SELECTION == 2){
            SQLiteDatabase database = this.getWritableDatabase();
            ContentValues cv = new ContentValues();
            // Iniciamos datos
            cv.put(ClientContract.NOMBRE_CLIENTE, cliente.getNombreCliente());
            cv.put(ClientContract.NOMBRE_LOCAL, cliente.getNombreLocal());
            cv.put(ClientContract.DIRECCION, cliente.getDireccion());
            cv.put(ClientContract.CIUDAD, cliente.getCiudad());
            cv.put(ClientContract.CORREO, cliente.getCorreoElectronico());
            cv.put(ClientContract.ZONA, cliente.getZona());
            cv.put(ClientContract.NUMERO_TELEFONO, cliente.getNumeroTelefono());
            cv.put(ClientContract.CODIGO_VENDEDOR, cliente.getCodigoVendedor());
            cv.put(ClientContract.RUC, cliente.getRUC());
            cv.put(ClientContract.STANDBY, cliente.getStandBy());
            // Insertamos
            database.insert(ClientContract.TABLE_NAME, null, cv);
            database.close();
        }

    }

    public Cliente getClienteById(int id){

        if(SELECTION == 2) {
            SQLiteDatabase database = this.getReadableDatabase();
            Cursor cursor = database.query(ClientContract.TABLE_NAME, ClientContract.COLUMNS, "_id = ?", new String[]{String.valueOf(id)}, null, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();

            }

            Cliente cliente = new Cliente();
            cliente.setNombreCliente(cursor.getString(cursor.getColumnIndex(ClientContract.NOMBRE_CLIENTE)));
            cliente.setNombreLocal(cursor.getString(cursor.getColumnIndex(ClientContract.NOMBRE_LOCAL)));
            cliente.setDireccion(cursor.getString(cursor.getColumnIndex(ClientContract.DIRECCION)));
            cliente.setCiudad(cursor.getString(cursor.getColumnIndex(ClientContract.CIUDAD)));
            cliente.setCorreoElectronico(cursor.getString(cursor.getColumnIndex(ClientContract.CORREO)));
            cliente.setZona(cursor.getString(cursor.getColumnIndex(ClientContract.ZONA)));
            cliente.setNumeroTelefono(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ClientContract.NUMERO_TELEFONO))));
            cliente.setCodigoVendedor(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ClientContract.CODIGO_VENDEDOR))));
            cliente.setRUC(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ClientContract.RUC))));
            cliente.setStandBy(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ClientContract.STANDBY))));
            cliente.setID(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ClientContract._ID))));

            cursor.close();
            return cliente;
        }else{
            return null;
        }
    }

    public int getClientCursorCount(){
        SQLiteDatabase database = this.getReadableDatabase();
        String query = "SELECT * FROM " + ClientContract.TABLE_NAME;
        Cursor cursor = database.rawQuery(query, null);

        return  cursor.getCount();
    }

    public List<Cliente> getAllClients(){

        if(SELECTION == 2) {
            List<Cliente> clienteList = new List<Cliente>();
            SQLiteDatabase database = this.getWritableDatabase();
            String query = "SELECT * FROM " + ClientContract.TABLE_NAME;
            Cursor cursor = database.rawQuery(query, null);

            Cliente cliente = null;
            if (cursor.moveToFirst()) {
                do {
                    cliente = new Cliente();
                    cliente.setNombreCliente(cursor.getString(cursor.getColumnIndex(ClientContract.NOMBRE_CLIENTE)));
                    cliente.setNombreLocal(cursor.getString(cursor.getColumnIndex(ClientContract.NOMBRE_LOCAL)));
                    cliente.setDireccion(cursor.getString(cursor.getColumnIndex(ClientContract.DIRECCION)));
                    cliente.setCiudad(cursor.getString(cursor.getColumnIndex(ClientContract.CIUDAD)));
                    cliente.setCorreoElectronico(cursor.getString(cursor.getColumnIndex(ClientContract.CORREO)));
                    cliente.setZona(cursor.getString(cursor.getColumnIndex(ClientContract.ZONA)));
                    cliente.setNumeroTelefono(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ClientContract.NUMERO_TELEFONO))));
                    cliente.setCodigoVendedor(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ClientContract.CODIGO_VENDEDOR))));
                    cliente.setRUC(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ClientContract.RUC))));
                    cliente.setStandBy(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ClientContract.STANDBY))));
                    cliente.setID(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ClientContract._ID))));


                    clienteList.addTop(cliente);
                } while (cursor.moveToNext());
            }

            cursor.close();
            return clienteList;
        }else{
            return null;
        }


    }

    public Cliente findClientByData(Object object){

        Cliente cliente = null;
        SQLiteDatabase database = this.getWritableDatabase();
        String query = "SELECT * FROM " + ClientContract.TABLE_NAME;
        Cursor cursor = database.rawQuery(query, null);
        if(object.getClass().equals(String.class)){
            if (cursor.moveToFirst()) {
                do {
                    if(cursor.getString(cursor.getColumnIndex(ClientContract.NOMBRE_CLIENTE)).equals(object) || cursor.getString(cursor.getColumnIndex(ClientContract.NOMBRE_LOCAL)).equals(object)){
                        cliente = getClienteById(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ClientContract._ID))));
                        break;
                    }
                }while(cursor.moveToNext());
            }
        }


        return cliente;
    }

    // END OF CLIENT METHODS -----------------------------------------------------------------------

}



And i Use in my MainActivity like this:
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


DatabaseHelper databaseHelperClient = new DatabaseHelper(InitActivity.this, 2);// Number two indicates to create table for client
            databaseHelperClient.addClient(client);
DatabaseHelper databaseHelperAdmin = new DatabaseHelper(InitActivity.this, 1); // Number one indicates to create table for admin
            databaseHelperAdmin.addAdmin(admin);


}

//但是在这种情况下,只创建了管理员

我希望创建“客户”表

2 个答案:

答案 0 :(得分:2)

在您更改数据库的版本之前,不会调用

onUpgrade

答案 1 :(得分:0)

要更改数据库时,必须调用onUpgrade,为此,每次更改数据库结构时都需要增加VERSION