大二寒假作业之Android
今日学习了Android操作SQLite数据库,对数据库实现了增删改查与创建。
首先创建一个类继承SQLDBHelper实现对数据库的创建
public void onCreate(SQLiteDatabase db) { String sql="create table person(id integer primary key autoincrement,name varchar,age varchar)"; db.execSQL(sql); db.execSQL("insert into person(name,age) values('李明','1')"); db.execSQL("insert into person(name,age) values('王五','19')"); db.execSQL("insert into person(name,age) values('大大','17')"); db.execSQL("insert into person(name,age) values('恋恋','12')"); Toast.makeText(context,"数据库已创建",Toast.LENGTH_LONG).show(); }
在activity层中分别写增删改查的代码:
public void createDB(View view) { MyDBHelper mydbh=new MyDBHelper(this,"mydb.db",1); SQLiteDatabase sqldb=mydbh.getReadableDatabase(); } public void insertDB(View view) { MyDBHelper mydbh=new MyDBHelper(this,"mydb.db",1); SQLiteDatabase sqldb=mydbh.getReadableDatabase(); ContentValues contentvalues=new ContentValues(); contentvalues.put("name","小小"); contentvalues.put("age","15"); long flag=sqldb.insert("person",null,contentvalues); sqldb.close(); Toast.makeText(this,"已加入"+flag+"条数据",Toast.LENGTH_LONG).show(); } public void updateData(View view) { MyDBHelper mydbh=new MyDBHelper(this,"mydb.db",1); SQLiteDatabase sqldb=mydbh.getReadableDatabase(); ContentValues contentvalues=new ContentValues(); contentvalues.put("name","明明"); contentvalues.put("age","12"); int flag=sqldb.update("person",contentvalues,"name=?",new String[]{"李明"}); Toast.makeText(this,"已有"+flag+"条数据修改",Toast.LENGTH_LONG).show(); } public void deleteDate(View view) { MyDBHelper mydbh=new MyDBHelper(this,"mydb.db",1); SQLiteDatabase sqldb=mydbh.getReadableDatabase(); int flag=sqldb.delete("person","id=1",null); Toast.makeText(this,"已有"+flag+"条数据删除",Toast.LENGTH_LONG).show(); } public void queryData(View view) { MyDBHelper mydbh=new MyDBHelper(this,"mydb.db",1); SQLiteDatabase sqldb=mydbh.getReadableDatabase(); Cursor cursor=sqldb.rawQuery("select * from person",null); if(cursor.moveToFirst()) { do{ String name=cursor.getString(cursor.getColumnIndex("name")); String age=cursor.getString(cursor.getColumnIndex("age")); Log.v("TAG",name+":"+age); }while(cursor.moveToNext()); } }