我是android新手。我之前没有使用过SQLite DB 我认为这是一个非常基本的问题,但我无法找到解决方案。
代码在这里(假设声明)
public void onCreate(SQLiteDatabase db) {
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + FORMULA + "("
+ CAT_CD + " TEXT ," + S_CAT_CD + " TEXT, PRIMARY
KEY(CAT_CD,S_CAT_CD))";
db.execSQL(CREATE_CATEGORIES_TABLE);
String CREATE_CAT_DESC_TABLE="CREATE TABLE "+ FORMULA_CAT_DESC + "
("+CAT_CD+" TEXT PRIMARY KEY, "+ DESC +" TEXT ) ";
db.execSQL(CREATE_CAT_DESC_TABLE);
String CREATE_CURRENCY_TABLE="CREATE TABLE "+ VI_CURRENCY + "("+
CURRENCY_CD +" TEXT PRIMARY KEY, "+ CURRENCY_SIGN +" TEXT ) ";
db.execSQL(CREATE_CURRENCY_TABLE);
String query= "INSERT INTO "+ VI_CURRENCY +" ("+CURRENCY_CD +",
"+CURRENCY_SIGN+ ") VALUES " +
"('INR', '₹'), " +
" ('USD','$') " +
"('JPY','¥') ";
db.execSQL(query);
}
前三个命令成功执行,而执行insert命令时,SQLite会抛出一个exeption。
答案 0 :(得分:1)
您可以为每条记录创建一个sql语句
String query1 = "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "('INR', '₹')" ;
String query2 = "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "('USD','$')" ;
String query3 = "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "('JPY','¥')" ;
db.execSQL(query1);
db.execSQL(query2);
db.execSQL(query3);
或者在一个语句中插入多个值,使用正确的sintax,就像这样:
String query = "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " +
"('INR', '₹'), " +
"('USD','$'), " +
"('JPY','¥')";
db.execSQL(query);
有关详细信息,请访问SqlLite
答案 1 :(得分:0)
如果要插入多个记录,则应该在键值对中的hashmap对象中获取数据。对它使用迭代器并在表中插入数据。
Map<String,String> myMap = new HashMap<>();
myMap.put("INR","₹");
myMap.put("USD","$");
myMap.put("JPY","¥");
Iterator it = myMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
String query1 = "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "("+ pair.getKey()+ "," + pair.getvalue()+)" ;
db.execSQL(query1);
it.remove(); // avoids a ConcurrentModificationException
}
答案 2 :(得分:0)
在Android中,写入操作很慢,所以在你的情况下,如果你有数百个数据,你可以在SQLite数据库中使用事务。
db.beginTransaction();
try {
for(/*your loop*/) {
String query = /*your query*/
db.execSQL(query);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
有关详细信息,请参阅this,官方文档。