sqlite更新查询无法正常运行

时间:2014-11-21 08:00:58

标签: android sqlite

我创建了这个类

public class MCount {

    public static final String TABLE_NAME = "Count";

    public static final String Columnname_ID = "Password_ID";

    public static final String Columnname_Counts = "counts";

    public static final String[] COLUMNS = { Columnname_ID, Columnname_Counts };

    private int password_id;
    private int counts;


    @Override
    public String toString() {
        return "MPassword[Password_ID=" + this.password_id + ", counts=" +  this.counts  + "]";
    }
    public MCount(int password_id, int counts) {
        this.password_id = password_id;

    }

    public int getPassword_id() {
        return password_id;
    }

    public void setPassword_id(int password_id) {
        this.password_id = password_id;
    }

    public int getcounts() {
        return counts;
    }

    public void setcounts(int counts) {
        this.counts = counts;
    }

}

和SQl帮助者课程

/**
 * Helper class which handles read/write from/to the Count.db
 * 
 * @author Eyog Yvon Léonce
 * 
 */
public class CountDbHelper extends SQLiteOpenHelper {

    private String password;

    private static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "Count.db";

    public CountDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // Default password for the password db. 
        this.password = "you are a bad boy! Desu ne!!!";
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_COUNT_TABLE = "CREATE TABLE " + MCount.TABLE_NAME + "( " + MCount.Columnname_ID + " INTEGER PRIMARY KEY, "
                  + MCount.Columnname_Counts + " INTEGER"   + ")";
        db.execSQL(CREATE_COUNT_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + MCount.TABLE_NAME);
        this.onCreate(db);
    }

    /**
     * Save the Password in the Count.db
     * 
     * @param password
     */
    public void setPassword(MCount password) {
        SQLiteDatabase db = this.getWritableDatabase(this.password);
        ContentValues values = new ContentValues();
        values.put(MCount.Columnname_ID, password.getPassword_id());
        values.put(MCount.Columnname_Counts, password.getcounts());
        db.insertWithOnConflict(MCount.TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_REPLACE);
        db.close();
    }

    /**
     * Load the Password from the Password.db
     * 
     * @return
     */
    public MCount getPassword() {
        MCount password = null;

        String query = "SELECT * FROM " + MCount.TABLE_NAME;
        SQLiteDatabase db = this.getWritableDatabase(this.password);
        Cursor cursor = db.rawQuery(query, null);

        if (cursor.moveToFirst()) {
            password = new MCount(Integer.parseInt(cursor.getString(0)), Integer.parseInt(cursor.getString(1)));
        }
        cursor.close();
        db.close();

        return password;
    }

    /**
     * Check if the Count.db has an entry in it
     * 
     * @return
     */
    public boolean hasPassword() {
        String query = "SELECT COUNT(*) FROM " + MCount.TABLE_NAME;
        SQLiteDatabase db = this.getWritableDatabase(this.password);
        Cursor cursor = db.rawQuery(query, null);
        try {
            if (cursor.moveToFirst()) {
                return cursor.getInt(0) > 0;
            }
        } catch (Exception e) {

        } finally {
            cursor.close();
            db.close();
        }
        return false;
    }

    /**
     * Add a failed try to the Count.db
     * 
     * @return
     */
    public int addCount() {

        int counts = 0 ;

        String query = "SELECT " + MCount.Columnname_Counts + " FROM " + MCount.TABLE_NAME;
        SQLiteDatabase db = this.getWritableDatabase(this.password);
        Cursor cursor = db.rawQuery(query, null);

        if (cursor.moveToFirst()) {
            counts = Integer.parseInt(cursor.getString(0));
            counts++;
            db.execSQL("UPDATE " + MCount.TABLE_NAME + " SET " + MCount.Columnname_Counts + "=" + counts);
        }

        Log.d("addTry()", "Added a Click. Count is now: " + counts);

        cursor.close();
        db.close();

        return counts;
    }
}

我试图获取按下给定按钮的次数,然后将其存储在数据库中。 我使用

在onlick方法中实例化助手类
    CountDbHelper helper = new  CountDbHelper (getApplicationContext());
    //MCount m_password = helper.getPassword();

    int tries = helper.addCount();
    Toast.makeText(getApplicationContext(),

            "You clicked "+ tries + " time already. ", Toast.LENGTH_SHORT).show();

它一直显示为零,我有点困惑。有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

在您的情况下,您是否在数据库中插入了记录?如果不是cursor.moveToFirst()将始终返回false,您将得到计数= 0

检查以下条件

public int addCount() {

            int counts = 0 ;

            String query = "SELECT " + MCount.Columnname_Counts + " FROM " + MCount.TABLE_NAME;
            SQLiteDatabase db = this.getWritableDatabase(this.password);
            Cursor cursor = db.rawQuery(query, null);

            if (cursor.moveToFirst()) {
                counts = Integer.parseInt(cursor.getString(0));
                counts++;
                db.execSQL("UPDATE " + MCount.TABLE_NAME + " SET " + MCount.Columnname_Counts + "=" + counts);
            } else {
              //insert record in database
    }

            Log.d("addTry()", "Added a Click. Count is now: " + counts);

            cursor.close();
            db.close();

            return counts;
        }

答案 1 :(得分:1)

您的表为空,因此SQL UPDATE语句无需更新。

您将需要使用插入和更新语句的组合,也称为“upsert'”。像这样:

private void upsertCount(SQLiteDatabase db, int counts) {
    ContentValues values = new ContentValues();
    values.put(MCount.Columnname_Counts, counts);
    int insertedCount = db.insert(MCount.TABLE_NAME, null, values);
    if (insertedCount == 0)
        db.update(MCount.TABLE_NAME, values, null, null);
}

BTW:请注意,这些upsert语句会影响MCount表中所有的记录。这可能是你想要的,但使用"表"是很奇怪的。存储"单个"值。表格用于多个值。存储它的更合适的位置是SharedPreferences。这是一个用于存储应用配置和设置的键值存储。

相关问题