我在将行插入数据库表时遇到问题。我有以下代码:
try {
myDB = jDB.getInstance(getApplicationContext()).db;
myDB.beginTransaction();
String sSQL = "INSERT INTO kosik (mnozstvi, cena, idVyrobek) VALUES ('" +
sMn + "', '" + sCena + "', '" + String.valueOf(iIDVyrobku) + "');";
myDB.execSQL(sSQL, null);
myDB.endTransaction();
} catch (SQLiteException e) {
e.printStackTrace();
}
类 jDB 如下:
public class jDB {
private static jDB dbInstance = null;
public static String DB_PATH;
public static SQLiteDatabase db = null;
private static final String DATABASE_NAME = "db.sqlite";
.
.
.
public static jDB getInstance(Context context)
{
if (dbInstance == null)
{
DB_PATH = "/data/data/" + context.getPackageName();
// if not exists database, copy new from assets
if (!isDataBaseExist())
{
try {
copyDataBase(context);
} catch (IOException ex)
{
Toast.makeText(context,
"" + ex.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
}
DB_PATH = DB_PATH + "/" + DATABASE_NAME;
db = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READWRITE);
// create singleton object
dbInstance = new jDB(context);
}
return dbInstance;
}
插入后,一切似乎都正常,但表中没有插入任何行...
我做错了什么?
谢谢,彼得
解决方案:
最后,有一个可行的解决方案:
try {
myDB = jDB.getInstance(getApplicationContext()).db;
myDB.beginTransaction();
ContentValues insertValues = new ContentValues();
insertValues.put("idVyrobek", String.valueOf(iIDVyrobku));
insertValues.put("mnozstvi", sMn);
insertValues.put("cena", sCena);
insertValues.put("poznamka", "");
myDB.insertOrThrow("kosik", null, insertValues);
myDB.setTransactionSuccessful();
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
myDB.endTransaction();
}
非常感谢您的帮助俾斯麦!