使用SQLite数据库

一、使用SQLiteOpenHelper类需要以下几个类

可以用JDBC相关数据库操作类进行类比

  • SQLiteOpenHelper--创建打开连接数据库;
  • SQLiteDatabase--PreparedStatement,通过这个类进行数据库的增删改查;
  • Cursor--ResultSet,查询时返回的数据集,根据这个类遍历查询结果;
  • ContentValue类,包装了HashMap类,该类用于存储键-值对的数据
    每个键-值对数据表示相应表中的列名和该列的数据
    键-->列名
    值-->列值
二、继承SQLiteOpenHelper类,打开创建数据库
class MyDatabaseHelp extends SQLiteOpenHelper{
        public MyDatabaseHelp(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }
        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {
            String sql="create table person(id integer primary key autoincrement," +
                    "name varchar(20)," +
                    "age integer)";
            sqLiteDatabase.execSQL(sql);
            Log.i("dayang","onCreate----------");
        }
        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
            String sql="create table person(id integer primary key autoincrement," +
                    "name varchar(20)" +
                    "age integer)";
            sqLiteDatabase.execSQL(sql);
        }
    }
在创建SQLiteDatabase类时,会创建数据库
MyDatabaseHelp help=new MyDatabaseHelp(this,"dayang",null,1);
SQLiteDatabase db=help.getReadableDatabase();
三、使用SQLiteDatabase类操作数据库

可以使用SQLiteDatabase类的execSQL(String sql)方法来执行sql语句

1.查询

也可以使用SQLiteDatabase类rawQuery()方法代替下面的查询

String sql ="select * from person";
db.rawQuery(sql,null);
MyDatabaseHelp help=new MyDatabaseHelp(this,"dayang",null,1);
SQLiteDatabase db=help.getWritableDatabase();
Cursor cursor=db.query("person",null,null,null,null,null,null);
while(cursor.moveToNext()){
    Log.i("dayang","id="+cursor.getString(cursor.getColumnIndex("id")));
    Log.i("dayang","name="+cursor.getString(cursor.getColumnIndex("name")));
    Log.i("dayang","age"+cursor.getString(cursor.getColumnIndex("age")));
}
2.插入

ContentValue类保存要插入的数据
相应的sql语句

insert into student(name,age) values('zhaoran','27');

 MyDatabaseHelp help=new MyDatabaseHelp(this,"dayang",null,1);
 SQLiteDatabase db=help.getWritableDatabase();
 ContentValues values=new ContentValues();
 values.put("name","zhaoran");//name对应person表中的name列
 values.put("age",27);//age对应person表中的age列
 long i= db.insert("person",null,values);//返回的是插入数据的位置
 Log.i("dayang","插入的位置"+i);
3.更新
 MyDatabaseHelp help=new MyDatabaseHelp(this,"dayang",null,1);
 SQLiteDatabase db=help.getWritableDatabase();
 ContentValues values=new ContentValues();
 values.put("name","dayu");
 int n=db.update("person",values,"id=?",new String[]{"3"});
 Log.i("dayang","返回影响数据行数:"+n);
4.删除
MyDatabaseHelp help=new MyDatabaseHelp(this,"dayang",null,1);
SQLiteDatabase db=help.getWritableDatabase();
int n=db.delete("person","id=?",new String[]{"6"});
Log.i("dayang","影响的行数"+n);

你可能感兴趣的:(使用SQLite数据库)