我正在使用mysql
从JSON
返回多行,但sqlite
只接受了一行,如何插入所有行:
MainActivity.java:
.....
if (!error) {
// user successfully exist in database
JSONObject user = jObj.getJSONObject("user");
String id = user.getString("id");
String sutdentId = user.getString("sutdentId");
String full_name = user.getString("full_name");
String year = user.getString("year");
String school = user.getString("school");
String level = user.getString("level");
// pass id ,fullname ,year ,school and level to
sqlite
db.addUser(id, sutdentId, full_name, year, school,
level);
.....
SqliteHandle.java
用于保存插入和表创建的方法:
public void addUser( String id, String sutdentId, String full_name
,String
year, String school, String level) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_userId, id);
values.put(KEY_Student, sutdentId);
values.put(KEY_Names, full_name);
values.put(KEY_Year, year);
values.put(KEY_School, school);
values.put(KEY_Level, level);
long Id = db.insert(TABLE_USER, null, values);
Log.d(TAG, "New user inserted into sqlite: " + Id);
if (Id > 0 ) {
Log.d(TAG, "New user inserted into database: " + Id);
}
else{
Log.d(TAG, "OOps! No data inserted in mysql ");
}
db.close(); // Closing database connection
}
答案 0 :(得分:0)
您需要遍历//a field that holds the compiled statement
private SQLiteStatement insStmt = null;
//assuming you have "JSONArray users" loaded;
for (int i = 0 ; i < users.length(); i++) {
JSONObject obj = users.getJSONObject(i);
String id = obj.getString("id");
String studentId = obj.getString("studentId");
String full_name = obj.getString("full_name");
String year = obj.getString("year");
String school = obj.getString("school");
String level = obj.getString("level");
addUser(id, sutdentId, full_name, year, school, level);
}
以插入所有行
您可以使用编译语句来更快地执行。
代码看起来大致如下:
function addUser(String id, String sutdentId, String full_name
,String year, String school, String level) {
if (insStmt == null) { //compile it once
String query = "INSERT into "+TABLE_NAME+"(id, studentId, full_name, year, school, level) VALUES (?,?,?,?,?,?)";
insStmt = myDataBase.compileStatement(query);
}
//bind the arguments
insStmt.bindAllArgsAsStrings(String[]{id, studentId, full_name, year, school, level});
//execute
insStmt.execute();
}
现在addUser函数看起来像这样(带有编译语句)。
@foreach($last_articles->chunk(3) as $row)
@foreach($row as $last_article)
@if($loop->index!=0) {{"in $loop"}} @endif
@endforeach
@if($loop->index!=0) {{"out $loop"}} @endif
@endforeach