开发者

Android: Inserting/Updating multiple records to SQL database

开发者 https://www.devze.com 2023-01-04 18:36 出处:网络
Ok, so perhaps I\'m completely missing something here, but I\'ve just started working with SQL and Android andfrom what I can see, updates and inserts back to the database need to be handled individua

Ok, so perhaps I'm completely missing something here, but I've just started working with SQL and Android and from what I can see, updates and inserts back to the database need to be handled individually?

I can retrieve a Cursor containing multiple records, but if I wanted to apply an update to each record in the cursor, I can only see how to do this individually, using ContentValues and Update(), and then the cursor requires reloading??

Same with if I wish to create multiple new records, these appear to be required to be inserted individually? Can I not create a List and bulk insert?

To me this seems slo开发者_StackOverflow社区w and cumbersome, and there has to be something I'm not yet aware of (searching for answers is failing me... likely due to using incorrect terms being new to android/java)

Here's a very simple example of what I basically what I want to achieve, however there must be a better way to achieve this functionality. (I know there are some other bad practises in here, just creating a quick eample)

public class HelloSQL extends Activity {

    SQLiteDatabase myDB = null;
    String TableName = "myTable";
    ContentValues myVals = new ContentValues();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String Data = "";

        // Create a Database.
        try {
            myDB = this.openOrCreateDatabase("myTestDB", MODE_PRIVATE, null);

            // Create a Table in the Database.
            myDB.execSQL("CREATE TABLE IF NOT EXISTS " + TableName
                    + " ( id INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + " Value1 INTEGER, Value2 INTEGER);");

            myDB.execSQL("DELETE FROM " + TableName);

            // insert value1
            for (int i = 0; i < 100; i++) {
                myVals.put("Value1", i);
                myDB.insert(TableName, null, myVals);
            }

            // retrieve data from database
            Cursor c = myDB.rawQuery("SELECT * FROM " + TableName, null);

            int colId = c.getColumnIndex("id");
            int col1 = c.getColumnIndex("Value1");
            int col2 = c.getColumnIndex("Value2");
            Random generator = new Random();

            // Loop through all values and update value2
            c.moveToFirst();
            if (c != null) {                
                do {                    
                    long id = c.getLong(colId);
                    int val1 = c.getInt(col1);
                    int randomVal = generator.nextInt(99);
                    myVals.put("Value1", val1);
                    myVals.put("Value2", randomVal);
                    myDB.insert(TableName, null, myVals);
                    myDB.update(TableName, myVals, "id=?",new String[] {Long.toString(id)});
                } while (c.moveToNext());
            }

            // requery data
            c = myDB.rawQuery("SELECT * FROM " + TableName, null);

            // display all values
            c.moveToFirst();
            if (c != null) {
                do {
                    int val1 = c.getInt(col1);
                    int val2 = c.getInt(col2);
                    Data = Data + Integer.toString(val1) + " " + Integer.toString(val2)  + "\n";
                } while (c.moveToNext());
            }           


            TextView tv = new TextView(this);
            tv.setText(Data);
            setContentView(tv);

        } catch (Exception e) {
            Log.e("Error", "Error", e);
        } finally {
            if (myDB != null)
                myDB.close();
        }
    }

Thanks in advance, don't expect anyone to re-write everything I've done here, but apoint in the right direction and links to a sample would be greatly appreciated.


updates and inserts back to the database need to be handled individually?

INSERT statements "need to be handled individually" on every SQL database that I can think of, on every platform I can think of. Anything supporting a bulk-insert pattern is a wrapper atop the SQL. The exception is an INSERT getting its data from a sub-SELECT off another table, which I do not think is what you are referring to.

UPDATE statements will update whatever rows you specify in your WHERE clause, which can be zero, one, or many. Again, this is the way SQL works.

but if I wanted to apply an update to each record in the cursor, I can only see how to do this individually, using ContentValues and Update(), and then the cursor requires reloading??

If the change is the same, use a single UPDATE statement and appropriate WHERE clause (either via the update() method, if that fits your update pattern, or via execSQL()). You need to requery() the Cursor because the Cursor holds the result set from the previous query, before your modifications.

Can I not create a List and bulk insert?

You are welcome to write Java code that does whatever you want. However, your constraint is SQL/SQLite.

0

精彩评论

暂无评论...
验证码 换一张
取 消