简体   繁体   中英

add large amount of data in SQLite android

I am new to android and maybe its a silly question but i am not getting it. See i am designing a game in which we give scores to some persons. So i want to store the names of the persons in a database while installation and then their scores set to 0 initially which will be updated according to what the users select. Here i am not able to figure out that how should i enter the data as it will be around 100 names and their scores. Using INSERT INTO() statement will make it like 100 statements. So is there any short method like can we do it through strings or something. Just guessing though. Any help would be appreciated.

You don't hard-code names or scores into your SQL statements. Instead, you use parameters.

var command = new SQLiteCommand()
command.CommandText = "INSERT INTO Scores (name, score) VALUES(@name, @score)";
command.CommandType = CommandType.Text;

foreach (var item in data)
{
   command.Parameters.Add(new SQLiteParameter("@name", item.Name));
   command.Parameters.Add(new SQLiteParameter("@score", item.Score));
   command.ExecuteNonQuery();
}

and then just loop through all of the names and scores.

I recommend you using a transaction. You can archive this stating you want to use a transaction with beginTransaction() , do all the inserts on makeAllInserts() with a loop and if everything works then call setTransactionSuccessful() to do it in a batch operation. If something goes wrong, on the finally section you will call endTransaction() without setting the success, this will execute a rollback.

db.beginTransaction();
try {
    makeAllInserts();
    db.setTransactionSuccessful();
}catch {
    //Error in between database transaction 
}finally {
    db.endTransaction();
}

For the makeAllInserts function, something like this could work out:

public void makeAllInserts() {
    for(int i = 0; i < myData.size(); i++) {
        myDataBase = openDatabase();
        ContentValues values = new ContentValues();
            values.put("name", myData.get(i).getName());
            values.put("score", myData.get(i).getScore());
        myDataBase.insert("MYTABLE", nullColumnHack, values);
    }
}

If you also want to know about the nullColumnHack here you have a good link -> https://stackoverflow.com/a/2663620/709671

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM