啊啊啊啊啊啊啊今天就写,炒鸡简单 数据库Sqlite的创建,库的增删改查

啦啦啦啦啦啦啦 写这个不用多长时间,我直接写代码注释都是些语句,Sql语句和Api来操作数据库 ,语句的参数我会注释 

SQLite数据库
创建数据库需要使用的api:SQLiteOpenHelper
必须定义一个构造方法:

//arg1:数据库文件的名字
//arg2:游标工厂
//arg3:数据库版本
public MyOpenHelper(Context context, String name, CursorFactory factory, int version){

}
//数据库被创建时会调用:onCreate方法
//数据库升级时会调用:onUpgrade方法

 

 

2创建数据库:

//创建OpenHelper对象
MyOpenHelper oh = new MyOpenHelper(getContext(), "person.db", null, 1);
//获得数据库对象,如果数据库不存在,先创建数据库,后获得,如果存在,则直接获得
SQLiteDatabase db = oh.getWritableDatabase();

* getWritableDatabase():打开可读写的数据库
* getReadableDatabase():在磁盘空间不足时打开只读数据库,否则打开可读写数据库
* 在创建数据库时创建表

public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table person (_id integer primary key autoincrement, name char(10), phone char(20), money integer(20))");
}

 


数据库的增删改查
一些简单的SQL语句:

 

insert into person (name, phone, money) values ('张三', '159874611', 2000);
delete from person where name = '李四' and _id = 4;
update person set money = 6000 where name = '李四';
select name, phone from person where name = '张三';

 

执行SQL语句实现增删改查

//插入
db.execSQL("insert into person (name, phone, money) values (?, ?, ?);", new Object[]{"张三", 15987461, 75000});
//查找
Cursor cs = db.rawQuery("select _id, name, money from person where name = ?;", new String[]{"张三"});
//测试方法执行前会调用此方法

protected void setUp() throws Exception {
super.setUp();
//    获取虚拟上下文对象
oh = new MyOpenHelper(getContext(), "people.db", null, 1);
}

 

###使用api实现增删改查

//插入

//以键值对的形式保存要存入数据库的数据
ContentValues cv = new ContentValues();
cv.put("name", "刘能");
cv.put("phone", 1651646);
cv.put("money", 3500);
//返回值是改行的主键,如果出错返回-1
long i = db.insert("person", null, cv);

// 删除

//返回值是删除的行数
int i = db.delete("person", "_id = ? and name = ?", new String[]{"1", "张三"});
* 修改

ContentValues cv = new ContentValues();
cv.put("money", 25000);
int i = db.update("person", cv, "name = ?", new String[]{"赵四"});
// 查询

//arg1:要查询的字段
//arg2:查询条件
//arg3:填充查询条件的占位符
Cursor cs = db.query("person", new String[]{"name", "money"}, "name = ?", new String[]{"张三"}, null, null, null);
while(cs.moveToNext()){
//    获取指定列的索引值
String name = cs.getString(cs.getColumnIndex("name"));
String money = cs.getString(cs.getColumnIndex("money"));
System.out.println(name + ";" + money);
}

 

事务:

什么是事务

 保证多条SQL语句要么同时成功,要么同时失败
 最常见案例:银行转账
 事务api

try {
//开启事务
db.beginTransaction();
...........
//设置事务执行成功
db.setTransactionSuccessful();
} finally{
//关闭事务
//如果此时已经设置事务执行成功,则sql语句生效,否则不生效
db.endTransaction();
}

 

 

先创建类MyOpenHelper 继承自SQLiteOpenHelper

 

public class MyOpenHelper extends SQLiteOpenHelper {

    public MyOpenHelper(Context context) {
        //1:数据库文件名字
        //2:游标工厂,游标等同于结果集,传null使用默认工厂
        //3:版本,不能小于1,用于升级
        super(context, "people.db", null, 1);
    }

    //创建数据库时调用
    @Override
    public void onCreate(SQLiteDatabase db) {
        //创建表
        db.execSQL("create table person(_id integer primary key autoincrement, name char(10), phone char(20), salary integer(10))");
    }

    //升级数据库时调用
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        System.out.println("数据库升级");
    }

}

 

 

XML文件 :新建测试类 并制定指令集 包,类库

 <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <instrumentation android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.ace.sqlite">
        </instrumentation>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <uses-library android:name="android.test.runner"/>    

 

public class Test extends AndroidTestCase{

    private MyOpenHelper oh;
    private SQLiteDatabase db;

    public void test(){
        //                                获取虚拟上下文
        MyOpenHelper oh = new MyOpenHelper(getContext());
        //如果数据库不存在,先创建,再打开,如果存在,就直接打开
        SQLiteDatabase db = oh.getWritableDatabase();
    }
    
    //测试方法执行前调用
    @Override
    protected void setUp() throws Exception {
        super.setUp();
        oh = new MyOpenHelper(getContext());
        db = oh.getWritableDatabase();
    }
    
    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
        db.close();
    }
    
    public void insert(){
//        db.execSQL("insert into person(name, phone, salary) values (?, ?, ?)", new Object[]{"亚索", "13503723845", 5000});
        db.execSQL("insert into person(name, phone, salary) values (?, ?, ?)", new Object[]{"德玛", "18543843843", 2000});
        db.execSQL("insert into person(name, phone, salary) values (?, ?, ?)", new Object[]{"蒙多", "12345678912", 3000});
    }
    
    public void delete(){
        db.execSQL("delete from person where name = ?", new Object[]{"亚索"});
    }
    
    public void update(){
        db.execSQL("update person set salary = ? where name = ?", new Object[]{5200, "亚索"});
    }
    
    public void select(){
        Cursor cursor = db.rawQuery("select * from person", null);
        //把指针移动至下一行
        while(cursor.moveToNext()){
            //先通过列名,获取列索引,然后再获取该列的内容
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String phone = cursor.getString(cursor.getColumnIndex("phone"));
            int salary = cursor.getInt(cursor.getColumnIndex("salary"));
            System.out.println(name + ";" + phone + ";" + salary);
        }
    }
    
    public void insertApi(){
        ContentValues values = new ContentValues();
        values.put("name", "女枪");
        values.put("phone", "1388888888");
        values.put("salary", "8000");
        //返回值-1,插入失败
        long l = db.insert("person", null, values);
        System.out.println(l);
    }
    
    public void deleteApi(){
        int i = db.delete("person", "_id = ?", new String[]{"6"});
        System.out.println(i);
    }
    
    public void updateApi(){
        ContentValues values = new ContentValues();
        values.put("name", "德邦");
        int i = db.update("person", values, "_id = ?", new String[]{"2"});
        System.out.println(i);
    }
    
    public void selectApi(){
        //arg1: 查询的字段
        //arg2: 查询的where条件
        //arg3: where条件的占位符
        Cursor cursor = db.query("person", null, null, null, null, null, null, null);
        while(cursor.moveToNext()){
            String name = cursor.getString(1);
            String phone = cursor.getString(2);
            int salary = cursor.getInt(3);
            System.out.println(name + ";" + phone + ";" + salary);
        }
    }
    
    public void transaction(){
        try{
            //开启事务
            db.beginTransaction();
            ContentValues values = new ContentValues();
            values.put("salary", 4500);
            db.update("person", values, "name = ?", new String[]{"亚索"});
            
            //清空values的内容
            values.clear();
            values.put("salary", 2500);
            db.update("person", values, "name = ?", new String[]{"的吗"});
            
//            int i = 1 / 0; //这句是为了打断事务,让数据回滚
            //设置事务执行成功,提交时如果这行代码没有执行过,就会回滚
            db.setTransactionSuccessful();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally{
            //关闭事务,提交数据
            db.endTransaction();
        }
    }
}

 转载的请注明出处 Acein20160131

你可能感兴趣的:(啊啊啊啊啊啊啊今天就写,炒鸡简单 数据库Sqlite的创建,库的增删改查)