0

我正在使用扩展 SQL Lite 开放助手的数据处理程序类创建数据库。我复制了一个示例,但此示例只有三列 ID、名称和技能。我想再添加三列力量、忠诚度和武器。该代码适用于这三列,但是一旦我再添加三列,它就不起作用了,并说它在创建数据库时找不到新列。我正在使用的代码如下..

公共类 DatabaseHandler 扩展 SQLiteOpenHelper {

private static final String DATABASE_NAME = "Cards.db";

private static final String TABLE_NAME = "card";

private static final String COL_ID = "id";

private static final String COL_NAME = "name";

private static final String COL_SKILL = "skill";

private static final String COL_STRENGTH = "strength";

private static final String COL_LOYALTY = "loyalty";

private static final String COL_WEAPON = "weapon";

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

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
            + COL_ID + " INTEGER PRIMARY KEY," + COL_NAME + " TEXT,"
            + COL_SKILL + " TEXT" + 
            COL_STRENGTH + "TEXT" 
            + COL_LOYALTY + "TEXT" + COL_WEAPON + "TEXT"+
            ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldNum, int newNum) {
    // Drop older table if exist and create fresh
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

public void addCard(Card card) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COL_ID, card.getID());
    values.put(COL_NAME, card.getName());
    values.put(COL_SKILL, card.getSkill());
    values.put(COL_STRENGTH, card.getStrength());
    values.put(COL_LOYALTY, card.getLoyalty());
    values.put(COL_WEAPON, card.getWeapon());
    db.insert(TABLE_NAME, null, values);
    db.close();
}

public List<Card> getAll() {
    List<Card> list = new ArrayList<Card>();
    String selectQuery = "SELECT  * FROM " + TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            Card card = new Card(cursor.getInt(0),
                    cursor.getString(1), cursor.getString(2))
                    cursor.getString(3), cursor.getString(4),
                    cursor.getString(5)
                    );
            list.add(card);
        } while (cursor.moveToNext());
    }
    return list;
}

public void removeAll() {
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

public void deleteCard(Card card) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_NAME, COL_ID + " = ?",
            new String[] { String.valueOf(card.getID()) });
    db.close();
}

public int updateCard(Card card) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COL_NAME, card.getName());
    values.put(COL_SKILL, card.getSkill());
    values.put(COL_STRENGTH, card.getStrength());
    values.put(COL_LOYALTY, card.getLoyalty());
    values.put(COL_WEAPON, card.getWeapon());
    return db.update(TABLE_NAME, values, COL_ID + " = ?",
            new String[] { String.valueOf(card.getID()) });
}

public Card getCard(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_NAME, new String[] { COL_ID, COL_NAME,
            COL_SKILL, 
            COL_STRENGTH, COL_LOYALTY, COL_WEAPON 
            }, COL_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
    }
    Card card = new Card(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2),
            cursor.getString(3), cursor.getString(4),
            cursor.getString(5)
            );
    return card;
}

}

我只是不知道它什么时候不喜欢我要插入的其他列。

我还有一个如下所示的卡片类。

公共类卡{

private int ID;

private String name;

private String skill;

private String strength; 

private String loyalty; 

private String weapon;


public Card(int ID, String name, String skill, String strength, String loyalty, String weapon) {
    this.ID = ID;
    this.name = name;
    this.strength = skill;
    this.skill = strength;
    this.loyalty = loyalty;
    this.weapon = weapon;
}

public String getName(){
    return this.name;
}

public void setName(String name){
    this.name = name;
}

public String getSkill(){
    return this.skill;
}

public void setSkill(String skill){
    this.skill = skill;
}

public String getStrength() {
    return this.strength;
}

public void setStrength(String strength) {
    this.strength = strength;
}

public String getLoyalty() {
    return this.loyalty;
}

public void setLoyalty(String loyalty) {
    this.loyalty = loyalty;
}

public String getWeapon() {
    return this.weapon;
}

public void setWeapon(String weapon) {
    this.weapon = weapon;
}

public int getID() {
    return ID;
}

public void setID(int iD) {
    ID = iD;
}

}

目前,我只是通过将数据库写入浏览类的日志来测试数据库的工作原理。我在这里使用的代码是。

公共类浏览扩展活动{

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout2);
    DatabaseHandler dh = new DatabaseHandler(this);

    Log.d("Database: ", "Dropping old table");
    dh.removeAll();

    Log.d("Database: ", "Inserting values..");
    dh.addCard(new Card(1, "Trevor", "11", "22", "33", "44"));
    dh.addCard(new Card(2, "Joseph", "49", "65", "87", "12"));
    dh.addCard(new Card(3, "Paul", "87", "12", "90", "01"));
    dh.addCard(new Card(4, "Mary", "30", "43", "12", "98"));

    Log.d("Database: ", "Listing all cards..");
    List<Card> list = dh.getAll();  
    for (Card lr : list) {
        String log = "ID:" + lr.getID() +" Name: " + lr.getName() + " Phone: " + lr.getSkill() + " Strength " + lr.getStrength()
                + " Loyalty: " + lr.getLoyalty() + " Weapon: " + lr.getWeapon();
        Log.d("Database: ", log); 
    }

    dh.deleteCard(new Card(1, "Trevor", "11", "22", "33", "44"));

    dh.updateCard(new Card(2, "Joseph", "36", "27", "87", "11"));

    Log.d("Database: ", "Re-listing all cards..");
    list = dh.getAll();
    for (Card lr : list) {
        String log = "ID:" + lr.getID() +" Name: " + lr.getName() + " Skill: " + lr.getSkill() + " Strength: " +lr.getStrength()
                + " Loyalty: " + lr.getLoyalty() + " Weapon: " + lr.getWeapon();
        Log.d("Database: ", log); 
    }

    Card retrieved = dh.getCard(3);
    Log.d("Database: ", "SINGLE: " + retrieved.getName());
}

}

有谁知道为什么它不会添加其他列?感谢您提供的任何帮助。

编辑**

我正在使用所有代码。当我运行应用程序时,我在 Log Cat 中得到以下信息

11-30 12:44:19.193:I/Database(364):sqlite 返回:错误代码 = 1,msg = 表卡没有名为忠诚度的列

11-30 12:44:19.213: E/Database(364): 插入 id=1 忠诚度=33 技能=11 力量=22 武器=44 名称=Trevor 时出错

11-30 12:44:19.213: E/Database(364): android.database.sqlite.SQLiteException: 表卡没有名为忠诚度的列:,编译时:插入卡(id,忠诚度,技能,力量,武器,名称)值(?,?,?,?,?,?);

11-30 12:44:19.213: E/Database(364): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)

11-30 12:44:19.213: E/Database(364): 在 android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:91)

11-30 12:44:19.213: E/Database(364): 在 android.database.sqlite.SQLiteCompiledSql.(SQLiteCompiledSql.java:64)

11-30 12:44:19.213: E/Database(364): 在 android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:80)

11-30 12:44:19.213: E/Database(364): 在 android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:36)

11-30 12:44:19.213: E/Database(364): 在 android.database.sqlite.SQLiteDatabase.compileStatement(SQLiteDatabase.java:1145)

11-30 12:44:19.213: E/Database(364): 在 android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1536)

11-30 12:44:19.213: E/Database(364): 在 android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1410)

11-30 12:44:19.213: E/Database(364): at uk.ac.tees.L1024329.DatabaseHandler.addCard(DatabaseHandler.java:96)

11-30 12:44:19.213: E/Database(364): at uk.ac.tees.L1024329.Browse.onCreate(Browse.java:22)

11-30 12:44:19.213: E/Database(364): 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

11-30 12:44:19.213: E/Database(364): 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

11-30 12:44:19.213: E/Database(364): 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)

11-30 12:44:19.213: E/Database(364): at android.app.ActivityThread.access$2300(ActivityThread.java:125)

11-30 12:44:19.213: E/Database(364): 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)

11-30 12:44:19.213: E/Database(364): 在 android.os.Handler.dispatchMessage(Handler.java:99)

11-30 12:44:19.213: E/Database(364): 在 android.os.Looper.loop(Looper.java:123)

11-30 12:44:19.213: E/Database(364): 在 android.app.ActivityThread.main(ActivityThread.java:4627)

11-30 12:44:19.213: E/Database(364): at java.lang.reflect.Method.invokeNative(Native Method)

11-30 12:44:19.213: E/Database(364): 在 java.lang.reflect.Method.invoke(Method.java:521)

11-30 12:44:19.213: E/Database(364): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)

11-30 12:44:19.213: E/Database(364): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)

11-30 12:44:19.213: E/Database(364): at dalvik.system.NativeStart.main(Native Method)

编辑* **

我已经尝试卸载/重新安装应用程序,我也尝试清除应用程序的数据,但都不起作用。

4

3 回答 3

2

看起来好像您错过了各个列名之间的逗号。它应该是

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
            + COL_ID + " INTEGER PRIMARY KEY," + COL_NAME + " TEXT,"
            + COL_SKILL + " TEXT," + 
            COL_STRENGTH + " TEXT, " 
            + COL_LOYALTY + " TEXT, " + COL_WEAPON + " TEXT"+
            ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

希望这可以帮助。

更新 这也是因为您没有在列名变量和列类型之间放置空格,因此您需要在 TEXT 一词之前放置一个空格,如我上面修改的代码中所示。

于 2012-11-30T14:46:56.593 回答
1

我有完全运行的代码。您可以尝试根据使用情况对其进行修改。

public class Database {

    static final String TAG="database";


    static final String DATABASE_NAME="YourDataBaseName";


    static final int DATABASE_VERSION=1;


    static final String DATABASE_COLLECT_TABLE="YourTableName1";
    static final String DATABASE_FOLLOWUP_TABLE="YourTableName2";



    static final String LeadNo="LeadNo";


    static final String Name="Name";


    static final String Process="Process";


    static final String NextAptDate="NextAptDate";


    static final String Time="Time";


    static final String ChequeNo="ChequeNo";


    static final String ChequeDate="ChequeDate";


    static final String Amount="Amount";


    static final String Bank="Bank";


    static final String Status="Status";


    static final String Remarks="Remarks";


    static final String id="ID";


    static final String CREATE_COLLECT_TABLE= "CREATE TABLE " + DATABASE_COLLECT_TABLE + "("
            + id + " INTEGER PRIMARY KEY AUTOINCREMENT, " + LeadNo + " TEXT NOT NULL, " + Name + " TEXT NOT NULL, "
            + Process + " TEXT NOT NULL, " + ChequeNo + " TEXT NOT NULL, " + ChequeDate + " TEXT NOT NULL, "
            + Amount + " TEXT NOT NULL, "+ Bank + " TEXT NOT NULL, "+ Status + " TEXT NOT NULL, "+ Remarks +" TEXT NOT NULL)";

    static final String CREATE_FOLLOWUP_TABLE= "CREATE TABLE " + DATABASE_FOLLOWUP_TABLE + " ("
            + id + " INTEGER PRIMARY KEY AUTOINCREMENT, " 
            + LeadNo + " TEXT NOT NULL, " 
            + Name + " TEXT NOT NULL, "
            + Process + " TEXT NOT NULL, " 
            + NextAptDate + " TEXT NOT NULL, " 
            + Time + " TEXT NOT NULL, "
            + Status + " TEXT NOT NULL, "
            + Remarks +" TEXT NOT NULL)";


    private final Context ctx;


    private DatabaseHelper dbHelper;


    private SQLiteDatabase sqlDB;


    private class DatabaseHelper extends SQLiteOpenHelper
    {


        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }


        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            Log.i(TAG, "Creating Collect Database :-"+CREATE_COLLECT_TABLE);
            Log.i(TAG, "Creating FollowUp Database :-"+CREATE_FOLLOWUP_TABLE);

            db.execSQL(CREATE_COLLECT_TABLE);
            db.execSQL(CREATE_FOLLOWUP_TABLE);
        }


        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            Log.w(TAG, "Upgrading Database from version "+ oldVersion + " to " + newVersion);
        }

    }


    public Database(Context context)
    {
        ctx=context;
    }

    public Database open() throws SQLException
    {
        dbHelper=new DatabaseHelper(ctx);
        sqlDB=dbHelper.getWritableDatabase();
        return this;
    }


    public void close()
    {
        dbHelper.close();
    }



    public long createCollect(String LeadNo,String Name,String Process,
            String ChequeNo,String ChequeDate,String Amount,
            String Bank,String Status,String Remarks)
    {
        ContentValues initialValues=new ContentValues();
        initialValues.put("LeadNo", LeadNo);
        initialValues.put("Name", Name);
        initialValues.put("Process", Process);
        initialValues.put("ChequeNo", ChequeNo);
        initialValues.put("ChequeDate", ChequeDate);
        initialValues.put("Amount", Amount);
        initialValues.put("Bank", Bank);
        initialValues.put("Status", Status);
        initialValues.put("Remarks", Remarks);

        //Checking Values
        Log.i("LeadNo", LeadNo);
        Log.i("Name", Name);
        Log.i("Process", Process);
        Log.i("ChequeNo", ChequeNo);
        Log.i("ChequeDate", ChequeDate);
        Log.i("Amount", Amount);
        Log.i("Bank", Bank);
        Log.i("Status", Status);
        Log.i("Remarks", Remarks);

        return sqlDB.insert(DATABASE_COLLECT_TABLE, null, initialValues);
    }


    public long createFollowUp(String LeadNo,String Name,String Process,
            String NextAptDate,String Time,String Status,String Remarks)
    {
        ContentValues values=new ContentValues();
        values.put("LeadNo", LeadNo);
        values.put("Name", Name);
        values.put("Process", Process);
        values.put("NextAptDate", NextAptDate);
        values.put("Time", Time);
        values.put("Status", Status);
        values.put("Remarks", Remarks);

        //Checking Values
        Log.i("LeadNo", LeadNo);
        Log.i("Name", Name);
        Log.i("Process", Process);
        Log.i("NextAptDate", NextAptDate);
        Log.i("Time", Time);
        Log.i("Status", Status);
        Log.i("Remarks", Remarks);

        return sqlDB.insert(DATABASE_FOLLOWUP_TABLE, null, values);
    }
}
于 2012-11-30T17:24:37.817 回答
0

如果我理解正确,似乎您忘记实现onUpgrade()方法在数据库上执行更改表以添加新列...或者如果您还没有发布应用程序,您可以只做一个清除数据和在不实现onUpgrade()的情况下重试...因为您的数据库已经使用旧列集创建,并且在您更新数据库版本号(这将触发onUpgrade())方法调用之前它不会创建新的.

于 2012-11-30T14:45:23.583 回答