gpt4 book ai didi

java - 使用内容值在 sqlite 中插入多行

转载 作者:太空宇宙 更新时间:2023-11-04 11:20:14 25 4
gpt4 key购买 nike

我使用 JSONmysql 返回多行,但只有一行被 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
}

最佳答案

您需要循环 jsonArray 来插入所有行。
您可以使用已编译的语句来使执行速度更快。

代码大致如下:

//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);
}

现在 addUser 函数将如下所示(带有编译后的语句)。

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();
}

关于java - 使用内容值在 sqlite 中插入多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44999444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com