数据库
SQLiteOpenHelper()是一个抽象类
getReadableDatabase()和getWritableDatabase()都可以创建或打开一个现有的数据库
四个参数,第一个参数是Context,第二个参数是数据库名,第三个参数允许我们在查询数据库的时候返回一个自定义的Cursor,一般传入null,第四个是数据库版本号,用于数据库的升级。
数据库操作
数据库文件会保存在/data/data/包名/databases/目录下。
1.创建数据库
cmd命令行下的数据库查看语句
首先adb shell->cd /data/data/当前的包名/database/->ls(查看)->
sqlite3 数据库名加.db-》
.table 显示当前数据库中含有的所有表 或者 .schema查看创建表的命令
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
/**创建一个类继承SQLiteOpenHelper
*然后把创建数据库的命令写成一个字符创
*/
public class MyDatabaseeHelper extends SQLiteOpenHelper{
public static final String CREATE_BOOK = "create table book ("+"id integer primary key autoincrement,"
+"author text,"
+"price real,"
+"pages integer,"
+"name text)";
public static final String CREATE_CATEGORY = "create table category("+
"id integer primary key autoincrement,"
+"category_name text,"
+"category_code integer)";
//创建一个context对象便于得到调用此类的类的当前环境,然后方便下面数据的传递
private Context mContext;
public MyDatabaseeHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
//执行创建表的语句
db.execSQL(CREATE_BOOK);
db.execSQL(CREATE_CATEGORY);
//创建成功后给予提示,正式使用时要删掉
Toast.makeText(mContext, "Create succed", Toast.LENGTH_SHORT).show();
}
/**数据库的升级更新语句
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists book");
db.execSQL("drop table if exists category");
onCreate(db);
}
}
"*****************在主类中使用数据库的语句*******************"
//创建一个数据库,数据库的名称为BookStore.db,必须以.db结尾
dbHelper = new MyDatabaseeHelper(this, "BookStore.db", null, 2);
//调用getWritableDatabase()创建一个新的数据库
dbHelper.getWritableDatabase();
2.升级数据库
public static final String CREATE_CATEGORY = "create table category("+
"id integer primary key autoincrement,"
+"category_name text,"
+"category_code integer)";
//这些为为了更新添加在第一个 MyDatabaseeHelper的语句
db.execSQL(CREATE_CATEGORY);
//这里先将已经存在的数据库中的表全删除,然后重新创建数据库
db.execSQL("drop table if exists book");
db.execSQL("drop table if exists category");
onCreate(db);
//将版本号升级以便会执行
dbHelper = new MyDatabaseeHelper(this, "BookStore.db", null, 3);
//再次调用getWritableDatabase()创建一个新的数据库
dbHelper.getWritableDatabase();
3.添加数据
inster( )方法接收三个参数,第一个参数是表名,第二个参数用于未指定添加数据的情况下给某些可为空的列自动赋值为null,一般设为null,第三个参数是一个ContenValues对象,它提供了一系列的put()方法重载,用于向ContenValues中添加数据。
//定义全局变量private MyDatabaseeHelper dbHelper;
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "This Da Vinci Code");
values.put("author", "Dan Brow");
values.put("pages", 454);
values.put("price", 16.69);
db.insert("book", null, values);
values.clear();
values.put("name", "The Lost Symbol");
values.put("author", "Dan Brow");
values.put("pages", 510);
values.put("price", 19.95);
db.insert("book", null, values);
"添加后的查看语句,在登录到当前数据库下的情况下,用cmd命令行查看,select * from book"
4.修改语句
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values= new ContentValues();
values.put("price", 10.99);
db.update("book", values, "name = ?", new String[]{"This Da Vinci Code"});
5.删除语句
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete("book", "pages > ?", new String[]{"500"});
6.查询语句
SQLiteDatabase db = dbHelper.getWritableDatabase();
//传入要查询的表名,其他值传入null,获得一个Cursor对象
Cursor cursor= db.query("book", null, null, null, null, null, null);
if(cursor.moveToFirst()){
do{
//得到列的索引项
String name = cursor.getString(cursor.getColumnIndex("name"));
String author = cursor.getString(cursor.getColumnIndex("author"));
int pages = cursor.getInt(cursor.getColumnIndex("pages"));
Double price = cursor.getDouble(cursor.getColumnIndex("price"));
Log.d("MainActivity", name);
Log.d("MainActivity", author);
Log.d("MainActivity",""+pages);
Log.d("MainActivity", ""+price);
//当没有下一个的时候返回false
}while(cursor.moveToNext());
}
//关闭索引
cursor.close();
//另外的部分不是这部分源码,后面的2,3,其中的2为偏移量,3为查询的数量。
Cursor cursor=db.query("user",null,null,null,null,null,null," 2 , 3 ");
query()方法 | 对应的SQL部分 | 描述 |
---|---|---|
table | from table_name | 指定查询的表名 |
columns | select column1,column2 | 指定查询的列名 |
selection | where column=value | 指定where的约束条件 |
selectionArgs | - | 为where中的占位符提供具体的值 |
groupBy | group by column | 指定需要group by 的列 |
having | having column=value | 对group by后的数据进一步约束 |
orderBy | order by column1,column2 | 指定查询结果的排序方式 |
6.使用事务(就是其中一条出错,全部都会回滚)
SQLiteDatabase db = dbHelper.getWritableDatabase();
//事务的开启
db.beginTransaction();
try{
db.delete("book", null, null);
ContentValues values= new ContentValues();
values.put("name", "Game of Thrones");
values.put("author", "George Martin");
values.put("pages", 720);
values.put("price", 20.85);
db.insert("book", null, values);
//事务已经执行成功
db.setTransactionSuccessful();
}catch(Exception e){
e.printStackTrace();
}finally {
//结束事务
db.endTransaction();
}
**升级数据库的最佳写法
"***********************第一版****************************"
public class MyDatabaseeHelper extends SQLiteOpenHelper{
public static final String CREATE_BOOK = "create table book ("+"id integer primary key autoincrement,"
+"author text,"
+"price real,"
+"pages integer,"
+"name text)";
private Context mContext;
public MyDatabaseeHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
"****************第二版,在向其中添加一个表*******************"
public class MyDatabaseeHelper extends SQLiteOpenHelper{
public static final String CREATE_BOOK = "create table book ("+"id integer primary key autoincrement,"
+"author text,"
+"price real,"
+"pages integer,"
+"name text)";
public static final String CREATE_CATEGORY = "create table category("+
"id integer primary key autoincrement,"
+"category_name text,"
+"category_code integer)";
private Context mContext;
public MyDatabaseeHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
db.execSQL(CREATE_CATEGORY);
Toast.makeText(mContext, "Create succed", Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch(oldVersion){
case 1:
db.execSQL(CREATE_CATEGORY);
default:
}
}
}
"****第三版,建立关联在Book表中添加一个category_id字段****"
public class MyDatabaseeHelper extends SQLiteOpenHelper{
public static final String CREATE_BOOK = "create table book ("+"id integer primary key autoincrement,"
+"author text,"
+"price real,"
+"pages integer,"
+"name text,"
//新添加的语句
+"category_id integer)";
public static final String CREATE_CATEGORY = "create table category("+
"id integer primary key autoincrement,"
+"category_name text,"
+"category_code integer)";
private Context mContext;
public MyDatabaseeHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
db.execSQL(CREATE_CATEGORY);
Toast.makeText(mContext, "Create succed", Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch(oldVersion){
case 1:
db.execSQL(CREATE_CATEGORY);
//添加语句
case 2:
db.execSQL("alter table Book add column category_id integer");
default:
}
}
}
//注意细节,switch中的每一个case的最后都是没有使用break的,这是为了在跨版本升级时,每一次的数据库修改都能被全部执行,不管怎样升级都能保证是最新的。
使用SQL的自带语句操作数据库
添加数据的方法
db.execSQL("insert into book (name,author,pages,price)values(?,?,?,?)",new String[]{"The Da Vinci Code","Dan Brown","454","16.96"});
更新数据的方法
db.execSQL("update book set price = ? where name=?",new String[]{"10.99","The Da Vinci Code"});
删除数据的方法
db.execSQL("delete from book where pages > ?",new String[]{"500"});
查询数据的方法
db.rawQuery("select * from book",null);