日期:2014-05-16 浏览次数:20537 次
代码 package com.webabcd.SQLite; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase.CursorFactory; // 数据库操作的 Helper 类 public class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context, String name, CursorFactory cursorFactory, int version) { super(context, name, cursorFactory, version); } @Override public void onCreate(SQLiteDatabase db) { // TODO 创建数据库后,对数据库的操作 } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO 更改数据库版本的操作 } @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); // TODO 每次成功打开数据库后首先被执行 } } Main.java 代码 package com.webabcd.SQLite; import java.util.Random; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class Main extends Activity { private DatabaseHelper dbHelper; private static final String DATABASE_NAME = "db.db"; private static final int DATABASE_VERSION = 1; private static final String TABLE_NAME = "employee"; TextView txtMsg; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); dbHelper = new DatabaseHelper(this, DATABASE_NAME, null, DATABASE_VERSION); txtMsg = (TextView) this.findViewById(R.id.txtMsg); Button btn1 = (Button) this.findViewById(R.id.btn1); btn1.setText("创建表"); btn1.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { CreateTable(); } }); Button btn2 = (Button) this.findViewById(R.id.btn2); btn2.setText("插入 3 条记录"); btn2.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { insertItem(); } }); Button btn3 = (Button) this.findViewById(R.id.btn3); btn3.setText("删除全部记录"); btn3.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { deleteItem(); } }); Button btn4 = (Button) this.findViewById(R.id.btn4); btn4.setText("更新指定数据"); btn4.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { updateItem(); } }); Button btn5 = (Button) this.findViewById(R.id.btn5); btn5.setText("显示全部数据"); btn5.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { showItems(); } }); Button btn6 = (Button) this.findViewById(R.id.btn6); btn6.setText("删除表"); btn6.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { dropTable(); } }); } // 创建数据表 private void CreateTable() { SQLiteDatabase db = dbHelper.getWritableDatabase(); String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (ID INTE