首页 > 解决方案 > Android SQLiteStatement 插入,没有任何反应

问题描述

我有一些来自 SoapObject 的数据,我想插入到 sqlite,为了获得更好的性能,我使用以下代码:

public void testInsert(String sql, SoapObject rs, int index) {
        try {
            sql = "INSERT INTO NSPMasterHarga (KdBarang, Wilayah, HargaJual1, HargaJual2) VALUES (?, ?, ?, ?)";
            theDatabase = getWritableDatabase();
            theDatabase.beginTransaction();

            String drop = "DROP TABLE IF EXISTS NSPMasterHarga";
            SQLiteStatement stmtDrop = theDatabase.compileStatement(drop);
            stmtDrop.execute();

            String create = "CREATE TABLE NSPMasterHarga (KdBarang TEXT PRIMARY KEY, Wilayah TEXT, HargaJual1 TEXT, HargaJual2 TEXT)";
            SQLiteStatement stmtCreate = theDatabase.compileStatement(create);
            stmtCreate.execute();

            SQLiteStatement stmt = theDatabase.compileStatement(sql);

            int count = rs.getPropertyCount();

            for (int i = 0; i < count; i++) {
                SoapObject row = (SoapObject) rs.getProperty(i);

                for (int j = 1; j <= index; j++) {
                    stmt.bindString(j, row.getProperty(j - 1).toString().replace("anyType{}", ""));
                }

                long entryID = stmt.executeInsert();
                stmt.clearBindings();
            }
        /*for (int i = 0; i < NUMBER_OF_ROWS; i++) {
            //generate some values

            stmt.bindString(1, randomName);
            stmt.bindString(2, randomDescription);
            stmt.bindDouble(3, randomPrice);
            stmt.bindLong(4, randomNumber);

            long entryID = stmt.executeInsert();
            stmt.clearBindings();
        }*/

            theDatabase.setTransactionSuccessful();
            theDatabase.endTransaction();

            theDatabase.close();
        }
        catch (Exception ex)
        {
            String err = ex.getMessage();
        }
    }

调试时,我没有任何错误,但数据没有插入我的 sqlite。任何想法或线索?

谢谢

标签: androidsoapinsertandroid-sqlite

解决方案


为了更好的性能

我不太确定您指的是代码的哪一部分。每次交互后打开和关闭数据库对性能来说是很糟糕的。SQLiteOpenHelper 负责所有这些,因此您无需手动执行任何操作。

尝试以下替代方法来插入条目:

public boolean addEntry(){
    db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put("column1", "value1");  // make sure the type corresponds to your sql column type
    values.put("column2", "value2");
    values.put("column3", "value3");
    values.put("column4Int", 1);

    long newRowId = db.insert(TABLE_NAME, null, values);
    Log.d("DBHelper", "Added row " + newRowId + " to DB.");

    return newRowId != -1;  // -1 means it failed
}

推荐阅读