android - 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。任何想法或线索?
谢谢
解决方案
为了更好的性能
我不太确定您指的是代码的哪一部分。每次交互后打开和关闭数据库对性能来说是很糟糕的。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
}
推荐阅读
- python - 有没有办法在 excel 和 power point 之间自动执行复制粘贴操作?
- google-apps-script - 如何解决共享 Google Apps 脚本库的“此应用被阻止”错误?
- java - 当状态码为 400 时,volley 返回空响应
- javascript - Echarts 未完全显示在 div 上。如何调整图表大小以适应 div?
- reactjs - 很难将 PayPal 与我的电子商务应用程序集成
- c++ - 有没有办法将 const double 更改为数组 C++?
- flutter - 如何使颤动显示来自json的大量数据
- unity3d - 为什么我的光线投射有时会朝错误的方向拍摄?(已解决
- javascript - html 和 javascript 滑块在本地工作,但在实时服务器中不起作用
- excel - 替换值条件