0.视频:http://www.imooc.com/video/3384
1.SQLiteOpenHelper笔记:
2.SQLiteOpenHelper.java代码:
1 import android.content.Context; 2 import android.database.sqlite.SQLiteDatabase; 3 import android.database.sqlite.SQLiteDatabase.CursorFactory; 4 import android.database.sqlite.SQLiteOpenHelper; 5 6 public class DBOpenHelper extends SQLiteOpenHelper { 7 8 public DBOpenHelper(Context context, String name) { 9 super(context, name,null, 1);10 // TODO Auto-generated constructor stub11 }12 public DBOpenHelper(Context context, String name, CursorFactory factory,13 int version) {14 super(context, name, factory, version);15 // TODO Auto-generated constructor stub16 }17 @Override18 public void onCreate(SQLiteDatabase db) {19 // TODO Auto-generated method stub20 //首次创建数据库时调用 一般有建库建表的操作21 db.execSQL("create table if not exists stutb(_id integer primary key autoincrement,name text not null,sex text not null,age integer not null)");22 db.execSQL("insert into stutb(name,sex,age)values('张三','女',18)");23 }24 25 @Override//当数据库的版本发生变化的时候 会自动执行26 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {27 // TODO Auto-generated method stub28 29 }30 31 }
3.MainActivity.java:
1 import com.example.sqlitedemo03.DBOpenHelper; 2 import com.example.sqlitedemo03.MainActivity; 3 4 import android.os.Bundle; 5 import android.app.Activity; 6 import android.database.Cursor; 7 import android.database.sqlite.SQLiteDatabase; 8 import android.util.Log; 9 import android.view.Menu;10 11 public class MainActivity extends Activity {12 13 @Override14 protected void onCreate(Bundle savedInstanceState) {15 super.onCreate(savedInstanceState);16 setContentView(R.layout.activity_main);17 DBOpenHelper helper = new DBOpenHelper(MainActivity.this, "stu.db");18 // helper.getReadableDatabase();//获取一个只读的数据库 只能查询 不能写入 不能更新19 SQLiteDatabase db = helper.getWritableDatabase();20 // db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy)21 Cursor c = db.rawQuery("select * from stutb", null);22 if (c!=null) {23 String [] cols = c.getColumnNames();24 while (c.moveToNext()) {25 for (String ColumnName : cols) {26 Log.i("info", ColumnName+":"+c.getString(c.getColumnIndex(ColumnName)));27 }28 }29 c.close();30 }31 db.close();32 }33 }
4.运行结果:
5.小记:构造方法重载的使用。