package com.db.test; import java.sql.SQLDataException; import android.R.string; import android.app.Activity; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.os.Bundle; import android.util.Log; public class DBTestActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); MyDataBaseOpenHelper mydb=new MyDataBaseOpenHelper(this); mydb.getReadableDatabase(); // mydb.insertDB("Tom", "BJING"); // mydb.insertDB("Jack", "NANJING"); // mydb.insertDB("Ting", "TIDDA"); mydb.deleteDB("Tom"); Cursor cs=mydb.queryDB(); cs.moveToFirst(); while(!cs.isLast()) { String str1=cs.getString(cs.getColumnIndex("name")); String str2=cs.getString(cs.getColumnIndex("address")); Log.d(">>>>姓名<<<<", str1); Log.d(">>>>地址<<<<", str2); cs.moveToNext(); } } class MyDataBaseOpenHelper extends SQLiteOpenHelper{ Context context; private static final String DB_NAME="mydb.db";//数据库的名字 private static final int VERSION=1;//数据库的版本 public MyDataBaseOpenHelper(Context context) { super(context, DB_NAME, null, VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub //建表语句执行 String sqlStr="create table person(_id integer primary key " + "autoincrement,name text,address text)"; //执行sql语句 db.execSQL(sqlStr); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub String sql="alter table person add age integer"; db.execSQL(sql); } /** * 插入数据 * @param name * @param address * @return */ public long insertDB(String name,String address) { SQLiteDatabase db=this.getWritableDatabase(); ContentValues cv=new ContentValues(); cv.put("name", name); cv.put("address", address); return db.insert("person", null, cv); } /** * 删除数据 * @param id * @return */ public long deleteDB(String name) { SQLiteDatabase db=this.getWritableDatabase(); String where="name=?"; String [] whereValue={name}; return db.delete("person", where, whereValue); } /** * 更新数据 * @param id * @param name * @param address * @return */ public long updateDB(String id ,String name,String address){ SQLiteDatabase db=this.getWritableDatabase(); ContentValues cv=new ContentValues(); cv.put("name", name); cv.put("address", address); String where="_id=?"; String[] whereValue={id}; return db.update("person", cv, where, whereValue); } public Cursor queryDB() { SQLiteDatabase db=this.getReadableDatabase(); Cursor cursor=db.query("person", null, null, null, null, null, null); return cursor; } } }