===================================================================================
1、sqlite介绍
官方网站:http://www.sqlite.org/
getReadableDatabase() getWritableDatabase() onCreate(sqliteDatabase db) onOpen(sqliteDatabase db) onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) close()
3、#sqlite3 test_mars_db
sqlite>.schema命令:都是以点开始的。显示当前数据库存在哪些表,以及表是怎么创建出来的!
===================================================================================
1、sqlite数据库的操作步骤:
(1) 先建一个类,
extends sqliteOpenHelper
(2)
写构造方法,四个参数的构造方法(Context context,String name,CursorFactory factory,int version){ super(context,name,factory,version); } 两个参数的构造方法(Context context,String name){ this(context,1); } 三个参数的构造方法(Context context,int version){ this(context,null,version); }
(3)
@override OnCreate方法(sqliteDatabase db){ db.execsql("create table user(id int,name varchar(20))"); } @override OnUpgrade(sqliteDatabase db,int newVersion){ 可以写一些操作 }
createDatabaseButtonListener中的onClick(View v){ //解释,DatabaseHelper是上面继承sqliteOpenHelper的那个类
DatabaseHelper dbHelper = new DatabaseHelper(当前类.this,"test_daming"); sqliteDatabase db = dbHelper.getReadableDatabase();
}
updateDatabaseButtonListener中的onClick(View v){ DatabaseHelper dbHelper = new DatabaseHelper(当前类.this,"test_daming",2); sqliteDatabase db = dbHelper.getReadableDatabase(); }
4、//插入数据库表的操作,写在了Button按钮的监听方法上了
insertButtonListener中的onClick(View v){ ContentValues values = new ContentValues(); values.put("id",1); values.put("name","daming"); DatabaseHelper dbHelper = new DatabaseHelper(当前类.this,"test_daming"); sqliteDatabase db = dbHelper.getWritableDatabase(); db.insert("user",values); }
5、//更新数据库表的操作,写在了Button按钮的监听方法上了
updateButtonListener中的onClick(View v){ DatabaseHelper dbHelper = new DatabaseHelper(当前类.this,"数据库名"); sqliteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name","Peking"); db.update("user",values,"id=?",new String[]{"1"}); }
6、//查找数据库表的操作,写在了Button按钮的监听方法上了
queryButtonListener中的onClick(View v){ DatabaseHelper dbHelper = new DatabaseHelper(当前类.this,数据名"); sqliteDatabase db = dbHelper.getWritableDatabse(); Cursor cursor = db.query("user",new String[]("id","name",new String[]{"1"},"id","id"})); while(cursor.moveToNext()){ String name = cursor.getString(cursor.getColumnIndex("name")); System.out.println("query-->"+name); } }
7、//删除数据库表的操作,写在了Button按钮的监听方法上了
deleteButtonListener中的onClick(View v){ DatabaseHelper dbHelper = new DatabaseHelper(当前类.this,数据名"); sqliteDatabase db = dbHelper.getWritableDatabse(); db.delete("student",new String[]{"1"}); System.out.println("删除表中id=1的记录"); }