SQLiteDatabase类:
一.使用sql语句操作数据库
SQLiteDatabase db = openOrCreateDatabase("database.db", MODE_PRIVATE,null);// (数据库名称,权限,数据工厂)
db.execSQL("create table if not exists usertb(_id integer primary key autoincrement,name text not null,age integer not null,sex text not null)");// 执行任何SQL语句
db.execSQL("insert into usertb(name,sex,age)values(‘张三‘,‘女‘,18)");//插入数据
Cursor:游标接口,提供了遍历查询结果的方法,如移动指针方法move(),获取列值方法getString()等常用方法:
-getCount()总记录条数
-isFirst()判断是否第一条记录
-isLast()判断是否最后一条记录
-moveToFirst()移动到第一条记录
-moveToLast()移动到最后一条记录
-move(int offset)移动到指定记录
-moveToNext()移动到下一条记录
-moveToprevious()移动到上一条记录
-getColumnIndexOrThrow(String columnName)据列名称获取列索引
-getInt(int columnIndex)获取指定列索引的int类型值
-getString(int columnIndex)获取指定列索引的String类型值
Cursor c=db.rawQuery(“select*from table“,null);
if(c!=null){
While(c.moveToNext()){}
}
package com.example.sqlitetest1; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //每个程序都有自己的数据库,默认情况下互不干扰 //创建数据库并打开 SQLiteDatabase db=openOrCreateDatabase("usertb",MODE_PRIVATE,null); String sqlcom="create table if not exists usertb(_id integer primary key autoincrement,name text,age integer,sex text)"; //执行sql语句 db.execSQL(sqlcom); //向数据库中插入数据 db.execSQL("insert into usertb(name,age,sex)values(‘张三‘,18,‘女‘)"); db.execSQL("insert into usertb(name,age,sex)values(‘张三‘,20,‘男‘)"); db.execSQL("insert into usertb(name,age,sex)values(‘李四‘,21,‘女‘)"); //查询 Cursor cs=db.rawQuery("select * from usertb",null); if(cs!=null){ while (cs.moveToNext()){ Log.i("info","id: "+cs.getString(cs.getColumnIndex("_id"))); Log.i("info","name: "+cs.getString(cs.getColumnIndex("name"))); Log.i("info","age: "+cs.getString(cs.getColumnIndex("age"))); Log.i("info","sex: "+cs.getString(cs.getColumnIndex("sex"))); Log.i("info","--------------------------------------------"); } cs.close(); } db.close(); } }
二.使用内置函数操作数据库
1. ContentValues类
存储一组可以被ContentResolver处理的值,可以理解为它的对象存储了多个键值对
2. 使用ContentValues和内置函数插入数据库
ContentValues values = new ContentValues();
values.put("name", "zhang76");
values.put("sex", "man");
values.put("age", 26);
sqLiteDatabase.insert("studentdb", null, values);
可以将values清空,并重新存值。
values.clear();
values.put("name", "张三");
values.put("sex", "man");
values.put("age", 27);
sqLiteDatabase.insert("studentdb", null, values);
3. 更新和删除
sqLiteDatabase.update("stutb",values,"_id">?,new String[]{"1"});//将全部ID>1的人的性别改成女;
sqLiteDatabase.delete("stutb","name like ?",new String[]{"%三%"});//删除所有名字中带有"三"的人
4. 通过Cursor类的getColumnNames()可以得到所有的列名
if(cursors!=null){
String[] columnNames = cursor.getColumnNames();
while (cursor.moveToNext()) { //moveToNext()可以移动到下一行
for(String columnName:columnNames) {
Log.i(TAG, cursor.getString(cursor.getColumnIndex(columnName)));
}
}
cursor.close();//关闭游标
}
sqLiteDatabase.close();
package com.example.sqlitetest2; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; public class MainActivity extends AppCompatActivity { private static final String TABLENAME="usertb"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SQLiteDatabase db2=openOrCreateDatabase("db",MODE_PRIVATE,null); String sqlcom="create table if not exists "+TABLENAME+"(_id integer primary key autoincrement,name text,age integer,sex text)"; db2.execSQL(sqlcom); ContentValues values=new ContentValues(); values.put("name","张三"); values.put("age",21); values.put("sex","男"); db2.insert(TABLENAME,null,values); values.clear(); values.put("name","李四"); values.put("age",24); values.put("sex","女"); db2.insert(TABLENAME,null,values); values.clear(); values.put("name","王五"); values.put("age",19); values.put("sex","男"); db2.insert(TABLENAME,null,values); values.clear(); values.put("name","张四"); values.put("age",19); values.put("sex","女"); db2.insert(TABLENAME,null,values); values.clear(); values.put("sex","女"); //将id>3的人的性别改为女 db2.update(TABLENAME,values,"_id>?",new String[]{"3"}); //删除名字中带有“三”的人 db2.delete(TABLENAME,"name like ?",new String[]{"%三%"}); //查询 Cursor cs=db2.query(TABLENAME,null,"_id>?",new String[]{"0"},null,null,"name");//查出id>0的值,即所有的 if(cs!=null){ String[] columnNames=cs.getColumnNames();//查询出所有的字段 while (cs.moveToNext()){ for (String columnName:columnNames) { Log.i("info", cs.getString(cs.getColumnIndex(columnName))); } } cs.close(); } db2.close(); } }
SQLiteOpenHelper类:
SQLiteOpenHelper帮助类,用于对数据库进行创建和升级。
实现两个方法:onCreate()方法用来实现创建数据库、onUpgrade()用来实现升级数据库
@Override//首次创建数据库的时候调用,一般用来建库/建表的操作
public void onCreate(SQLiteDatabase db) {
// TODO 自动生成的方法存根
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)");
db.execSQL("insert into stutb(name,sex,age)values(‘张三‘,‘女‘,18)");
}
@Override//当数据库的版本发生变化的时候会自动执行
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO 自动生成的方法存根
}
Demo:
MyOpenHelper.class:
package com.example.sqlitetest3; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by xch on 2016/9/19. */ public class MyOpenHelper extends SQLiteOpenHelper{ private static final String TABLENAME="stu"; public MyOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override//首次创建数据库时调用,一般用来创建数据库 创建表 public void onCreate(SQLiteDatabase db) { String sqlcom="create table if not exists "+TABLENAME+"(_id integer primary key autoincrement,name text,age integer,sex text)"; db.execSQL(sqlcom); db.execSQL("insert into "+TABLENAME+"(name,sex,age)values(‘yang‘,‘男‘,20)"); } @Override//版本更新时调用 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
MainActivity.class
package com.example.sqlitetest3; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MyOpenHelper helper=new MyOpenHelper(MainActivity.this,"stu",null,1); helper.getReadableDatabase();//获取一个只读的数据库,不能写入,不能更新,只能查询 SQLiteDatabase database=helper.getWritableDatabase(); Cursor cs=database.rawQuery("select * from stu",null); if(cs!=null){ String[] colmnNames=cs.getColumnNames(); while(cs.moveToNext()){ for (String cln:colmnNames ) { Log.i("info","ColumnNames:"+cs.getString(cs.getColumnIndex(cln))); } } cs.close(); } database.close(); } }