Android数据库问题:无法在同一数据库中创建表

时间:2018-06-11 10:01:56

标签: android android-studio

我正面临一个问题,而且无法解决。我已经搜索并尝试了所有内容,但仍然无法修复此问题。

我创建了两个单独的类,并且都使用相同的数据库DGWallet.db第一个类是DatabaseHelper.java

package com.example.dell.sql;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.dell.model.User;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;

public class DatabaseHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 3;

   // Database Name
    private static final String DATABASE_NAME = "DGWallet.db";

    // User table name
    private static final String TABLE_USER = "users";

    // User Table Columns names

    private static final String COLUMN_NAME = "name";
    private static final String COLUMN_BIRTH_DATE = "date";
    private static final String COLUMN_EMAIL = "email";
    private static final String COLUMN_PASSWORD = "password";
    private static final String COLUMN_PHONE = "phone_no";

    // create table sql query
    private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
            + COLUMN_PHONE + " INTEGER PRIMARY KEY ," + COLUMN_NAME + " TEXT," + COLUMN_BIRTH_DATE  + " DATE, "
            + COLUMN_EMAIL + " TEXT," + COLUMN_PASSWORD + " TEXT" + ")";


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


    }

    /**
     * Constructor
     *
     * @param context
     */
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_USER_TABLE);
    }


    /**
     * This method is to create user record
     *
     * @param user
     */
    public void addUser(User user) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_PHONE, user.getPhone());
        values.put(COLUMN_NAME, user.getName());
        values.put(COLUMN_BIRTH_DATE, user.getBirthDate());
        values.put(COLUMN_EMAIL, user.getEmail());
        values.put(COLUMN_PASSWORD, user.getPassword());

        // Inserting Row
        db.insert(TABLE_USER, null, values);
        db.close();
    }

    /**
     * This method is to fetch all user and return the list of user records
     *
     * @return list
     */
    public List<User> getAllUser() {
        // array of columns to fetch
        String[] columns = {
                COLUMN_PHONE,
                COLUMN_NAME,
                COLUMN_BIRTH_DATE,
                COLUMN_EMAIL,
                COLUMN_PASSWORD
        };
        // sorting orders
        String sortOrder =
                COLUMN_NAME + " ASC";
        List<User> userList = new ArrayList<User>();

        SQLiteDatabase db = this.getReadableDatabase();

        // query the user table
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id,user_name,user_email,user_password FROM user ORDER BY user_name;
         */
        Cursor cursor = db.query(TABLE_USER, //Table to query
                columns,    //columns to return
                null,        //columns for the WHERE clause
                null,        //The values for the WHERE clause
                null,       //group the rows
                null,       //filter by row groups
                sortOrder); //The sort order


        // Traversing through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                User user = new User();
                user.setPhone(Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_PHONE))));
                user.setName(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
                user.setBirthDate(cursor.getString(cursor.getColumnIndex(COLUMN_BIRTH_DATE)));
                user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_EMAIL)));
                user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_PASSWORD)));
                // Adding user record to list
                userList.add(user);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();

        // return user list
        return userList;
    }

    /**
     * This method to check user exist or not
     *
     * @param email
     * @return true/false
     */
    public boolean checkUser(String email) {

        // array of columns to fetch
        String[] columns = {
                COLUMN_NAME
        };
        SQLiteDatabase db = this.getReadableDatabase();

        // selection criteria
        String selection = COLUMN_EMAIL + " = ?";

        // selection argument
        String[] selectionArgs = {email};

        // query user table with condition
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com';
         */
        Cursor cursor = db.query(TABLE_USER, //Table to query
                columns,                    //columns to return
                selection,                  //columns for the WHERE clause
                selectionArgs,              //The values for the WHERE clause
                null,                       //group the rows
                null,                      //filter by row groups
                null);                      //The sort order
        int cursorCount = cursor.getCount();
        cursor.close();
        db.close();

        if (cursorCount > 0) {
            return true;
        }

        return false;
    }

    /**
     * This method to check user exist or not
     *
     * @param email
     * @param password
     * @return true/false
     */
    public boolean checkUser(String email, String password) {

        // array of columns to fetch
        String[] columns = {
                COLUMN_NAME
        };
        SQLiteDatabase db = this.getReadableDatabase();
        // selection criteria
        String selection = COLUMN_EMAIL + " = ?" + " AND " + COLUMN_PASSWORD + " = ?";

        // selection arguments
        String[] selectionArgs = {email, password};

        // query user table with conditions
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com' AND user_password = 'qwerty';
         */
        Cursor cursor = db.query(TABLE_USER, //Table to query
                columns,                    //columns to return
                selection,                  //columns for the WHERE clause
                selectionArgs,              //The values for the WHERE clause
                null,                       //group the rows
                null,                       //filter by row groups
                null);                      //The sort order

        int cursorCount = cursor.getCount();

        cursor.close();
        db.close();
        if (cursorCount > 0) {
            return true;
        }

        return false;
    }


}

从这个类开始创建表,我已经从adb shell中检查过了:

sqlite3 DG                                                                     <
DGWallet.db         DGWallet.db-shm     DGWallet.db-wal
qlite3 DGWallet.db                                                            <
SQLite version 3.22.0 2018-01-22 18:45:57
Enter ".help" for usage hints.
sqlite> .table
android_metadata  users           
sqlite> select * from users;

但是,当我使用类似类型的代码时,为了创建另一个表,我收到一条错误消息。此外,表格创建代码没有被执行。我通过删除逗号检查了这一点,但仍然没有抛出任何错误。

package com.example.dell.sql;

import android.content.Context;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.ContactsContract;

import com.example.dell.model.Add_User;


import java.util.ArrayList;
import java.util.List;

    public class DatabasePersonDetails extends SQLiteOpenHelper {

        public static final int DATABASE_VERSION = 3;
        public static final String DATABASE_NAME = "DGWallet.db";

        private static final String TABLE_USERS = "persondetails";


        public static final String COLUMN_FIRST_NAME = "firstname";
        public static final String COLUMN_MIDDLE_NAME = "middlename";
        public static final String COLUMN_LAST_NAME = "lastname";
        public static final String COLUMN_ADDRESS = "address";
        public static final String COLUMN_PHONE = "phone";
        public static final String COLUMN_CREDIT_BALANCE = "credit_balance";
        public static final String COLUMN_DEBIT_BALANCE = "debit_balace";

        private static final String CREATE_USER_TABLE =
                "CREATE TABLE " + DatabasePersonDetails.TABLE_USERS + " (" +
                        COLUMN_PHONE + " INTEGER PRIMARY KEY," +
                        COLUMN_FIRST_NAME + " TEXT," +
                        COLUMN_MIDDLE_NAME + " TEXT," +
                        COLUMN_LAST_NAME + "Text," +
                        COLUMN_ADDRESS + "Text," +
                        COLUMN_CREDIT_BALANCE + "Real," +
                        COLUMN_DEBIT_BALANCE + "Real" + ")";

        public DatabasePersonDetails(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);

        }

        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_USER_TABLE);
        }

        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // This database is only a cache for online data, so its upgrade policy is
            // to simply to discard the data and start over
            db.execSQL(CREATE_USER_TABLE);
            onCreate(db);
        }

        public void add_user(Add_User add_user){


            // Gets the data repository in write mode
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(COLUMN_PHONE, add_user.getPhone());
            values.put(COLUMN_FIRST_NAME, add_user.getFirstname());
            values.put(COLUMN_MIDDLE_NAME,add_user.getMiddlename());
            values.put(COLUMN_LAST_NAME,add_user.getLastname());
            values.put(COLUMN_ADDRESS,add_user.getAddress());
            values.put(COLUMN_CREDIT_BALANCE,add_user.getCredit_bal());
            values.put(COLUMN_DEBIT_BALANCE,add_user.getDebit_bal());

            db.insert(TABLE_USERS, null,values);
            db.close();

        }

        public List<Add_User> getAllUsers(){
            String [] columns = {
                    COLUMN_PHONE,
                    COLUMN_FIRST_NAME,
                    COLUMN_MIDDLE_NAME,
                    COLUMN_LAST_NAME,
                    COLUMN_ADDRESS,
                    COLUMN_CREDIT_BALANCE,
                    COLUMN_DEBIT_BALANCE
            };

            String sortOrder = COLUMN_FIRST_NAME + "ASC";

            List<Add_User> add_userList=new ArrayList<Add_User>();

            SQLiteDatabase db = this.getReadableDatabase();

            Cursor cursor = db.query(TABLE_USERS, //Table to query
                    columns,    //columns to return
                    null,        //columns for the WHERE clause
                    null,        //The values for the WHERE clause
                    null,       //group the rows
                    null,       //filter by row groups
                    sortOrder); //The sort order

            if (cursor.moveToFirst()) {
                do {
                    Add_User addUser = new Add_User();
                    addUser.setPhone(Long.parseLong(cursor.getString(cursor.getColumnIndex(COLUMN_PHONE))));
                    addUser.setFirstname(cursor.getString(cursor.getColumnIndex(COLUMN_FIRST_NAME)));
                    addUser.setMiddlename(cursor.getString(cursor.getColumnIndex(COLUMN_MIDDLE_NAME)));
                    addUser.setLastname(cursor.getString(cursor.getColumnIndex(COLUMN_LAST_NAME)));
                    addUser.setAddress(cursor.getString(cursor.getColumnIndex(COLUMN_ADDRESS)));
                    addUser.setCredit_bal(Float.parseFloat(cursor.getString(cursor.getColumnIndex(COLUMN_CREDIT_BALANCE))));
                    addUser.setDebit_bal(Float.parseFloat(cursor.getString(cursor.getColumnIndex(COLUMN_DEBIT_BALANCE))));
                    ;
                    // Adding user record to list
                    add_userList.add(addUser);
                } while (cursor.moveToNext());
            }
            cursor.close();
            db.close();

            // return user list
            return add_userList;

        }

   }

我尝试将版本号从3更改为4,并且还检查了模拟器的版本号。

3.22.0 2018-01-22 18:45:57 0c55d179733b46d8d0ba4d88e01a25e10677046ee3da1d5b1581e86726f2alt2

我从模拟器中删除了应用,清理了项目,然后再次检查,但问题仍然存在。

这是错误消息:

E/SQLiteDatabase: Error inserting firstname=null address=xyz debit_balace=5000.0 phone=7022013810 credit_balance=5000.0 middlename=Rao lastname=Lambu
                  android.database.sqlite.SQLiteException: no such table: persondetails (code 1 SQLITE_ERROR): , while compiling: INSERT INTO persondetails(firstname,address,debit_balace,phone,credit_balance,middlename,lastname) VALUES (?,?,?,?,?,?,?)
                      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:901)
                      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:512)
                      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                      at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                      at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1562)
                      at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
                      at com.example.dell.sql.DatabasePersonDetails.add_user(DatabasePersonDetails.java:74)
                      at com.example.dell.digitalwallet.Add_Users.PostDataToSqlite(Add_Users.java:118)
                      at com.example.dell.digitalwallet.Add_Users$1.onClick(Add_Users.java:95)
                      at android.view.View.performClick(View.java:6597)
                      at android.view.View.performClickInternal(View.java:6574)
                      at android.view.View.access$3100(View.java:778)
                      at android.view.View$PerformClick.run(View.java:25881)
                      at android.os.Handler.handleCallback(Handler.java:873)
                      at android.os.Handler.dispatchMessage(Handler.java:99)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6649)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)

Add_User.java

public class Add_User {

    private String firstname;
    private String middlename;
    private String lastname;
    private String address;
    private long Phone_No;
    private float Credit_bal;
    private float Debit_bal;
    // private String birth_date;

    public String getFirstname() {return firstname;}

    public void setFirstname(String firstname) {
        this.firstname =firstname;

    }

    public String getMiddlename() {return middlename;}

    public void setMiddlename(String middlename){
        this.middlename=middlename;
    }



    public String getLastname() {return lastname;}

    public void setLastname(String lastname) {
        this.lastname=lastname;
    }

    public String getAddress() {return address;}

    public void setAddress(String address){
        this.address=address;
    }


    public long getPhone() {
        return Phone_No;
    }

    public void setPhone(long Phone_no) {

        this.Phone_No = Phone_no;
    }

    public float getCredit_bal(){return Credit_bal;}

    public void setCredit_bal(float Credit_bal){
        this.Credit_bal=Credit_bal;
    }

    public float getDebit_bal(){return Debit_bal;}

    public void setDebit_bal(float Debit_bal){
        this.Debit_bal=Debit_bal;
    }

}

任何人都可以帮助我。感谢。

2 个答案:

答案 0 :(得分:1)

如评论中所述。问题是DatabasePersonDetails.onCreate(SQLiteDatabase db)也没有 在尝试将用户添加到表之前,正在调用DatabasePersonDetails.onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion),因此,表不存在。

在尝试添加数据之前,请确保调用创建表的两种方法之一。 (最快修复)。

我的建议是将所有表创建添加到同一个地方,这样在创建数据库时,就可以在其中创建所有必需的表。

答案 1 :(得分:0)

我更改了数据库,而不是使用DGWallet.db。这很有效。

为什么我保持这样的设计的原因是,这两者都用于不同的屏幕,并用于存储不同的信息。使用此设计可以更轻松地进行调试。