以编程方式在Android

时间:2018-02-05 08:57:34

标签: java android sqlite android-sqlite

我创建了一个医生数据库。我想从代码本身将数据插入数据库,但我无法弄清楚如何在数据库中插入多行。有人可以帮我解释一下语法吗?我有30位医生的名单。

package net.simplifiedcoding.navigationdrawerexample;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class Doctor extends Activity implements View.OnClickListener {
SQLiteDatabase db;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_doctor);
    TextView textView= (TextView) findViewById(R.id.textView5);
    String doc= getIntent().getStringExtra("type");
    String authentication= getIntent().getStringExtra("auth");
    textView.setText(doc);
    db=openOrCreateDatabase("DoctorDB", Context.MODE_PRIVATE,null);
    db.execSQL("CREATE TABLE IF NOT EXISTS doctor(Name VARCHAR,degree VARCHAR,address VARCHAR,phnumber VARCHAR);");
    db.execSQL("INSERT INTO 'DoctorDB' ('Name', 'degree','address', 'phnumber')VALUES ('"Sujoy Khan"')");
}

2 个答案:

答案 0 :(得分:0)

为查询创建占位符:

String placeholder = "INSERT INTO 'DoctorDB' ('Name', 'degree','address', 'phnumber')VALUES ('%s', '%s', '%s', '%s')";

然后在周期中使用String.format()%s替换为实际值:

for(...) {
    String sql = String.format (placeholder, name, degree, address, phnumber);
    db.execSQL(sql);
}

答案 1 :(得分:0)

您最好使用方法beginTransaction()setTransactionSuccessful()endTransaction()进行批量操作。您首先需要一个SQLiteDatabase实例,并使用ContentValues您将在数据库中插入所有需要的信息。一个例子是:

SQLiteDatabase database = DbOpenHelper.getInstance(context).getWritableDatabase();
database.beginTransaction();

for (Doctor doctor : doctors) {
    ContentValues contentValues = new ContentValues();
    contentValues.put("Name", doctor.name);
    contentValues.put("Degree", doctor.degree);

    database.insert(TABLE_DOCTOR, null, contentValues);
}

database.setTransactionSuccessful();
database.endTransaction();