GVKun编程网logo

Sqlite3.0数据库在iPhone中的应用

22

如果您对Sqlite3.0数据库在iPhone中的应用感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解Sqlite3.0数据库在iPhone中的应用的各种细节,此外还有关于Android在Sql

如果您对Sqlite3.0数据库在iPhone中的应用感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解Sqlite3.0数据库在iPhone中的应用的各种细节,此外还有关于Android在Sqlite3中的应用及多线程使用数据库的建议、Android在Sqlite3中的应用及多线程使用数据库的建议(实例代码)、Django:使用sqlite3作为数据库在Heroku上部署应用程序、iphone – iOS应用程序sqlite3上的脱机缓存已损坏的实用技巧。

本文目录一览:

Sqlite3.0数据库在iPhone中的应用

Sqlite3.0数据库在iPhone中的应用

这两天终于把sqlite数据库在iPhone中的应用搞懂了。。

还是那些增删改查,却没有存储过程之类的,数据类型也少了。为了初始化数据,自己感觉有两种方案可以执行,都可以使数据初始化一次:一种是使用主键约束(sid integer PRIMARY KEY),一种是在AppDelegate文件中初始化。这样我自己感觉可以仅调用一次数据信息。

下面是iPhone程序中使用的部分代码信息:

第一部分:用于检测该信息中是否已存在mydatabase.sql数据库信息,若存在则直接打开,若不存在则新建本数据库文件,然后在打开该数据库文件。

-(BOOL)open{

//获取路径数组

NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

//获取路径数组中第一个信息

Nsstring*documentsDirectory=[pathsobjectAtIndex:0];

//选择创建的文件信息

Nsstring*path=[documentsDirectorystringByAppendingPathComponent:@"mydatabase.sql"];
NSFileManager*fileManager=[NSFileManagerdefaultManager];

BOOLfind=[fileManagerfileExistsAtPath:path];

if(find) {

if(sqlite3_open([pathUTF8String],&database)!=sqlITE_OK) {

sqlite3_close(database);

NSLog(@"Sorror,opening db file Error");//使用NSLog用于显示错误状态

returnNO;

}

returnYES;

}

else{

sqlite3_close(database);

NSLog(@"Sorror,opening db file Error,and Not Link Db");

returnNO;

}

第二部分:创建表 ,可以由用户设置主键和sqlServer一样也可以设置自动增长信息。

//创建学生表信息

-(BOOL)CreateTableStudent:(sqlite3*)db{

char*errorMsg;

// 本信息是用于删除表

//NSLog(@"first Delete tabel");

//Nsstring *DeleteTable=@"drop table student";

//

//if (sqlite3_exec(db,[DeleteTable UTF8String],NULL,&errorMsg)==sqlITE_OK) {

////sqlite3_close(db);

////NSAssert1(0,@"Error creating table: %s",errorMsg);

// NSLog(@"delect table------------------------");

//}

//NSLog(@"delect table");

//表中设置主键可消除重复添加

Nsstring*createsql=@"Create table if not exists student(sid integer PRIMARY KEY autoincrement,name text,sex text,age integer)";

//在sqlite中不可以直接使用字符串信息,必须使用UTF8String进行数据格式转化,但是至今不明白为什么

//这样做

if(sqlite3_exec(db,[createsqlUTF8String],NULL,&errorMsg)!=sqlITE_OK) {

sqlite3_close(db);

NSAssert1(0,@"Error creating table: %s",errorMsg);

NSLog(@"studentTable is created successfuly");//显示创建成功

return YES;


第三部:初始化数据信息(增加数据信息),数据参数是从1开始的,values(?,?,?)使用问号作为占位符,占位符的信息是从1开始计数的,这与查找是得Where语句后面的参数形式不是一致。

//学生表中初始化数据信息

-(void)InsertIntoStudentTable:(sqlite3*)database{

char* insert="insert or replace into student(sid,name,sex,age) values(?,?);";

sqlite3_stmt*stmt;

intcount=0;//用于计数,可以观察到数据信息插入的情况

if(sqlite3_prepare_v2(database,insert,-1,&stmt,nil)==sqlITE_OK) {

sqlite3_bind_int(stmt,1,1);

sqlite3_bind_text(stmt,2,[@"zhixuan"UTF8String],NULL);

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,3,[@"F"UTF8String],4,23);

count=count+1;//用于计数,可以观察到数据信息插入的情况

if(sqlite3_step(stmt)!=sqlITE_DONE) {

NSLog(@"insert error .....");

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,2);

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,[@"liyan"UTF8String],[@"M"UTF8String],65)"> count=count+1;//用于计数,可以观察到数据信息插入的情况

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,3);

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,[@"zhangzhixuan"UTF8String],65)"> count=count+1;

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,4);

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,[@"zhangliguang"UTF8String],21);

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,5);

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,[@"liyanfen"UTF8String],19);

count=count+1;//用于计数,可以观察到数据信息插入的情况

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,6);

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,[@"zhangsan"UTF8String],65)"> count=count+1;//用于计数,可以观察到数据信息插入的情况

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,7);

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,[@"wanggang"UTF8String],8);

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,[@"lisi"UTF8String],25);

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,9);

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,[@"yanhua"UTF8String],20);

count=count+1;//用于计数,可以观察到数据信息插入的情况

//10

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,10);

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,[@"xueyan"UTF8String],nil)==sqlITE_OK){

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,11);

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,[@"wangxiaogang"UTF8String],31);

count=count+1;//用于计数,可以观察到数据信息插入的情况

NSLog(@"error insert data....");

NSLog(@"count is %d",count);//使用NSLOg显示数据插入的情况

第四部分:无参数查询表信息,设计思路,获取表中全部数据,根据数据信息进行分类分别存储在不同动态数据中,然后将所用动态数据放在一个动态数据组中用于返回数据载体。该思路所涉及的数组比较多,也是最大缺点之一,也可以考虑使用实体类作为信息载体,最后把实体类放在数组中设为消息。

//查找数据库中Student表的数据信息

-(NSMutableArray*)selectStudentInfoTableFromDb:(sqlite3*)db{

//检测数据库信息链接方式

[selfopen];

//设置外部消息载体

NSMutableArray*studentArray=[[NSMutableArrayalloc]init];

//设置本方法中信息载体

NSMutableArray *sidArray;

NSMutableArray *snameArray;

NSMutableArray *sSexarray;

NSMutableArray *sAge;

snameArray=[[NSMutableArrayalloc]init];

sSexarray=[[NSMutableArrayalloc]init];

sidArray=[[NSMutableArrayalloc]init];

sAge=[[NSMutableArrayalloc]init];

NSLog(@" Yes,Begin Reading info");

Nsstring*sqlString=@"SELECT sid,age FROM student";

if(sqlite3_prepare_v2(database,[sqlStringUTF8String],65)">

NSLog(@"yes,you ok");

while(sqlite3_step(stmt)==sqlITE_ROW) {

//NSLog(@"------------------------");

NSIntegersid=sqlite3_column_int(stmt,0);

char*name=(char*)sqlite3_column_text(stmt,65)"> char*Sex=(char*)sqlite3_column_text(stmt,65)"> NSIntegerAge=sqlite3_column_int(stmt,65)"> //设置接受信息

Nsstring*sidStri=[[Nsstringalloc]initWithFormat:@"%d",sid];

Nsstring*NameStr=[[Nsstringalloc]initWithUTF8String:name];

Nsstring*SexStr=[[Nsstringalloc]initWithUTF8String:Sex];

Nsstring*AgeStr=[[Nsstringalloc]initWithFormat:@"%d",Age];

[sidArrayaddobject:sidStri];

[snameArrayaddobject:NameStr];

[sSexarrayaddobject:SexStr];

[sAgeaddobject:AgeStr];

NSLog(@"数据读写错误,数据库访问错误!!");

[studentArrayaddobject:sidArray];

[studentArrayaddobject: snameArray];

[studentArrayaddobject:sSexarray];

[studentArrayaddobject:sAge];

returnstudentArray;

第五部分:设置带参信息查询sqlite3_bind_int(stmt,sid);用于设置参数信息,参数信息从1开始,而在

是从0开始设置参数,这也是我犯错误的地方。。

//通过Id信息查找详细信息

//带参数信息查询

-(NSMutableArray*)selectStudentInfoTableByIDFromdb:(NSInteger)sid {

//打开检测链接

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,age FROM student where sid=?";

//设置参数

ottom:5px; padding-top:0px; padding-bottom:0px; border-top-width:0px; border-right-width:0px; border-bottom-width:0px; border-left-width:0px; border-style:initial; border-color:initial; list-style-type:none; list-style-position:initial; border-style:initial; border-color:initial; word-wrap:normal; word-break:normal; line-height:21px; color:rgb(50,sid);

//设置接受信息,进行数据格式转换

//加载信息

[studentArrayaddobject:sidStri];

[studentArrayaddobject:NameStr];

[studentArrayaddobject:SexStr];

[studentArrayaddobject:AgeStr];

本代码中还用很多不太清楚的地方,我本人虽然有些地方用到了,可是还是不是和理解,比如为什么非要使用UTF8格式信息,等相关内部信息问题。谢谢大家的阅读。。

把代码和自己的理解晒出来希望和有共同爱好的相互学习。

转自:http://blog.sina.com.cn/s/blog_879201790100vqd7.html

Android在Sqlite3中的应用及多线程使用数据库的建议

Android在Sqlite3中的应用及多线程使用数据库的建议

1、首先先建立一个DatabaseHelper类,继承自sqliteOpenHelper,用于建立数据库,并可更新数据库例如我新建了两张表

public class DatabaseHelper extends sqliteOpenHelper {


    private static DatabaseHelper _databaseHelper;

    private static final String TAG = DatabaseHelper.class.getSimpleName();

    public synchronized static DatabaseHelper getInstance(Context context)
    {
        if(_databaseHelper==null)
        {
            _databaseHelper = new DatabaseHelper(context,"cgjlb",null,2);
        }
        return _databaseHelper;
    }

    public synchronized static void destoryInstance(){
        if(_databaseHelper!=null){
            _databaseHelper=null;
        }
    }

    public DatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable sqliteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(sqliteDatabase sqliteDatabase) {
        //主表记录
        String sql = "create table t_share(_id integer primary key autoincrement,sharenum text,sharename text,shareprice real,sharelastprice real,addtime text,uptime text,bl real)";
        sqliteDatabase.execsql(sql);

        //记录历史表
        sql = "create table t_sharehis(_id integer primary key autoincrement,shareid integer, shareprice real,uptime text)";
        sqliteDatabase.execsql(sql);
    }

    @Override
    public void onUpgrade(sqliteDatabase sqliteDatabase, int i, int i1) {

        Log.d(TAG, "onUpgrade: upddatabase");

        sqliteDatabase.execsql("drop table t_share");
        sqliteDatabase.execsql("drop table t_sharehis");
        onCreate(sqliteDatabase);
    }
}

 

2、编写数据库具体操作类、增删改查我都写了

public class ShareDbService {

    sqliteDatabase db = null;
    DatabaseHelper databaseHelper;
    private static final String TAG = ShareDbService.class.getSimpleName();

    public ShareDbService(Context context) {
        databaseHelper = DatabaseHelper.getInstance(context);
        db = databaseHelper.getWritableDatabase();
    }

    public void addShareInfo(ShareBean shareBean)
    {
        int Id = getShareId(shareBean.getShareNum());
        if(Id==-1) {
            ContentValues values = new ContentValues();
            values.put("sharenum", shareBean.getShareNum());
            values.put("sharename", shareBean.getShareName());
            values.put("shareprice", shareBean.getSharePrice());
            values.put("sharelastprice", shareBean.getShareLastPrice());
            values.put("uptime", shareBean.getUptime());
            values.put("addtime",shareBean.getAddtime());
            double shareprice = shareBean.getSharePrice();
            double sharelastprice = shareBean.getShareLastPrice();
            double bl = (sharelastprice-shareprice)/shareprice*100;

            values.put("bl", new DecimalFormat("0.00").format(bl));
            db = databaseHelper.getWritableDatabase();
            db.insert("t_share", null, values);
            ShareHisBean shareHisBean = new ShareHisBean();
            shareHisBean.setShareId(getShareId(shareBean.getShareNum()));
            shareHisBean.setSharePrice(shareBean.getSharePrice());
            shareHisBean.setUpTime(shareBean.getUptime());
            addShareHis(shareHisBean);
            db.close();
        }
    }

    private void addShareHis(ShareHisBean shareHisBean){

        ContentValues values = new ContentValues();
        values.put("shareid", shareHisBean.getShareId());
        values.put("shareprice", shareHisBean.getSharePrice());
        values.put("uptime", shareHisBean.getUptime());
        db = databaseHelper.getWritableDatabase();
        db.insert("t_sharehis", null, values);
        db.close();
    }

    public void refreshShare(ShareHisBean shareHisBean,double sharePrice){
        try {
            //更新信息主表
            db = databaseHelper.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put("uptime", shareHisBean.getUptime());
            values.put("sharelastprice", shareHisBean.getSharePrice());
            String[] args = {String.valueOf(shareHisBean.getShareId())};
            double sharelastprice = shareHisBean.getSharePrice();
            double bl = (sharelastprice - sharePrice) / sharePrice * 100;
            values.put("bl", bl);
            db.update("t_share", values, "_Id=?", new String[]{String.valueOf(shareHisBean.getShareId())});
            //添加记录
            values = new ContentValues();
            values.put("shareid", shareHisBean.getShareId());
            values.put("shareprice", shareHisBean.getSharePrice());
            values.put("uptime", shareHisBean.getUptime());
            db.insert("t_sharehis", null, values);
        }catch(Exception ex){
            ex.printstacktrace();
        }
        finally {
            db.close();
        }

    }

    public void delShare(String Id){
        db = databaseHelper.getWritableDatabase();
        db.delete("t_share","_Id=?",new String[]{Id});
        db.delete("t_sharehis","shareid=?",new String[]{Id});
        db.close();
    }

    private int getShareId(String shareNum) {
        db = databaseHelper.getReadableDatabase();
        String sql = "select _Id from t_share where sharenum='" + shareNum + "'";
        int Id = -1;
        Cursor cursor = db.rawQuery(sql, null);
        if (cursor != null) {
            while (cursor.movetoNext()){
                Id = cursor.getInt(0);
            }
        }
        cursor.close();
        db.close();
        return Id;
    }

    public List<ShareBean> getShareList(){
        db = databaseHelper.getReadableDatabase();
        List<ShareBean> shareBeans = new ArrayList<>();
        String sql = "select _id,sharenum,sharename,shareprice,sharelastprice,uptime,addtime,bl from t_share order by _Id desc";
        Cursor cursor = db.rawQuery(sql, null);
        if (cursor != null) {
            while (cursor.movetoNext()){
                ShareBean shareBean = new ShareBean();
                shareBean.set_Id(cursor.getInt(0));
                shareBean.setShareNum(cursor.getString(1));
                shareBean.setShareName(cursor.getString(2));
                shareBean.setSharePrice(cursor.getDouble(3));
                shareBean.setShareLastPrice(cursor.getDouble(4));
                shareBean.setUptime(cursor.getString(5));
                shareBean.setAddtime(cursor.getString(6));
                shareBean.setBl(cursor.getDouble(7));
                shareBeans.add(shareBean);
            }
        }
        cursor.close();
        db.close();
        return shareBeans;
    }

    public List<ShareHisBean> getShareListHis(int ShareId){
        db = databaseHelper.getReadableDatabase();
        List<ShareHisBean> shareHisBeans = new ArrayList<>();
        String sql = "select _id,shareid,shareprice,uptime from t_sharehis where shareid='"+String.valueOf(ShareId)+"' order by _id desc";
        Cursor cursor = db.rawQuery(sql, null);
        if (cursor != null) {
            while (cursor.movetoNext()){
                ShareHisBean shareHisBean = new ShareHisBean();
                shareHisBean.set_Id(cursor.getInt(0));
                shareHisBean.setShareId(cursor.getInt(1));
                shareHisBean.setSharePrice(cursor.getDouble(2));
                shareHisBean.setUpTime(cursor.getString(3));
                shareHisBeans.add(shareHisBean);
            }
        }
        cursor.close();
        db.close();
        return shareHisBeans;
    }

    public ShareBean getShareInfo(int ShareId) {
        db = databaseHelper.getReadableDatabase();
        ShareBean shareBean = new ShareBean();
        //_id integer primary key autoincrement,sharenum text,sharename text,shareprice real,sharelastprice real,addtime text,uptime text,bl real
        String sql = "select _id,sharenum,sharename,shareprice,sharelastprice,addtime,uptime,bl from t_share where _Id='"+String.valueOf(ShareId)+"'";
        Cursor cursor = db.rawQuery(sql, null);
        if (cursor != null) {
            if (cursor.movetoNext()){
                shareBean.set_Id(cursor.getInt(0));
                shareBean.setShareNum(cursor.getString(1));
                shareBean.setShareName(cursor.getString(2));
                shareBean.setSharePrice(cursor.getDouble(3));
                shareBean.setShareLastPrice(cursor.getDouble(4));
                shareBean.setAddtime(cursor.getString(5));
                shareBean.setUptime(cursor.getString(6));
                shareBean.setBl(cursor.getDouble(7));
            }
        }
        cursor.close();
        db.close();
        return shareBean;
    }
}

3、实际中的应用,就举一个例子吧,数据库操作不用开新线程,直接在主线程里弄就行

 ShareDbService shareDbService = new ShareDbService(getContext());
 shareDbService.delShare(String.valueOf(shareBean.get_Id()));

4、需要注意的是sqlite不支持多线程,最好是能批量修改,否则很麻烦,如果一定要多线程 ,比如循环请求网络更新数据库时,可以使用CountDownLatch,先将数据弄在一个集合里,等子线程全部执行完成后,再更新数据库。此方法具体应用如下

先声明一个变量

CountDownLatch latch;

实际应用代码

//设置多线程 个数,一共用多少个线程一定要写清楚,后面是要减的。
        latch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {            
            new Thread(()-> {
                try {
                    //网络请求等操作
                } catch (Exception e) {
                    e.printstacktrace();
                } finally {
                    //这里会自动减1操作,一定要写。
                    latch.countDown();
                }
            }).start();
        };
        try {
            latch.await();
           //最后执行主程序,比如更新数据库
            Toast.makeText(getContext(), "刷新成功", Toast.LENGTH_SHORT).show();
        } catch (InterruptedException e) {
            e.printstacktrace();
        }

 

Android在Sqlite3中的应用及多线程使用数据库的建议(实例代码)

Android在Sqlite3中的应用及多线程使用数据库的建议(实例代码)

1、首先先建立一个DatabaseHelper类,继承自SQLiteOpenHelper,用于建立数据库,并可更新数据库例如我新建了两张表

public class DatabaseHelper extends SQLiteOpenHelper {

    private static DatabaseHelper _databaseHelper;
    private static final String TAG = DatabaseHelper.class.getSimpleName();
    public synchronized static DatabaseHelper getInstance(Context context)
    {
        if(_databaseHelper==null)
        {
            _databaseHelper = new DatabaseHelper(context,"cgjlb",null,2);
        }
        return _databaseHelper;
    }
    public synchronized static void destoryInstance(){
        if(_databaseHelper!=null){
            _databaseHelper=null;
    public DatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //主表记录
        String sql = "create table t_share(_id integer primary key autoincrement,sharenum text,sharename text,shareprice real,sharelastprice real,addtime text,uptime text,bl real)";
        sqLiteDatabase.execSQL(sql);
        //记录历史表
        sql = "create table t_sharehis(_id integer primary key autoincrement,shareid integer, shareprice real,uptime text)";
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        Log.d(TAG, "onUpgrade: upddatabase");
        sqLiteDatabase.execSQL("drop table t_share");
        sqLiteDatabase.execSQL("drop table t_sharehis");
        onCreate(sqLiteDatabase);
}

2、编写数据库具体操作类、增删改查我都写了

public class ShareDbService {

    SQLiteDatabase db = null;
    DatabaseHelper databaseHelper;
    private static final String TAG = ShareDbService.class.getSimpleName();
    public ShareDbService(Context context) {
        databaseHelper = DatabaseHelper.getInstance(context);
        db = databaseHelper.getWritableDatabase();
    }
    public void addShareInfo(ShareBean shareBean)
    {
        int Id = getShareId(shareBean.getShareNum());
        if(Id==-1) {
            ContentValues values = new ContentValues();
            values.put("sharenum", shareBean.getShareNum());
            values.put("sharename", shareBean.getShareName());
            values.put("shareprice", shareBean.getSharePrice());
            values.put("sharelastprice", shareBean.getShareLastPrice());
            values.put("uptime", shareBean.getUptime());
            values.put("addtime",shareBean.getAddtime());
            double shareprice = shareBean.getSharePrice();
            double sharelastprice = shareBean.getShareLastPrice();
            double bl = (sharelastprice-shareprice)/shareprice*100;
            values.put("bl", new DecimalFormat("0.00").format(bl));
            db = databaseHelper.getWritableDatabase();
            db.insert("t_share", null, values);
            ShareHisBean shareHisBean = new ShareHisBean();
            shareHisBean.setShareId(getShareId(shareBean.getShareNum()));
            shareHisBean.setSharePrice(shareBean.getSharePrice());
            shareHisBean.setUpTime(shareBean.getUptime());
            addShareHis(shareHisBean);
            db.close();
        }
    private void addShareHis(ShareHisBean shareHisBean){
        ContentValues values = new ContentValues();
        values.put("shareid", shareHisBean.getShareId());
        values.put("shareprice", shareHisBean.getSharePrice());
        values.put("uptime", shareHisBean.getUptime());
        db.insert("t_sharehis", null, values);
        db.close();
    public void refreshShare(ShareHisBean shareHisBean,double sharePrice){
        try {
            //更新信息主表
            values.put("uptime", shareHisBean.getUptime());
            values.put("sharelastprice", shareHisBean.getSharePrice());
            String[] args = {String.valueOf(shareHisBean.getShareId())};
            double sharelastprice = shareHisBean.getSharePrice();
            double bl = (sharelastprice - sharePrice) / sharePrice * 100;
            values.put("bl", bl);
            db.update("t_share", values, "_Id=?", new String[]{String.valueOf(shareHisBean.getShareId())});
            //添加记录
            values = new ContentValues();
            values.put("shareid", shareHisBean.getShareId());
            values.put("shareprice", shareHisBean.getSharePrice());
            db.insert("t_sharehis", null, values);
        }catch(Exception ex){
            ex.printStackTrace();
        finally {
    public void delShare(String Id){
        db.delete("t_share","_Id=?",new String[]{Id});
        db.delete("t_sharehis","shareid=?",new String[]{Id});
    private int getShareId(String shareNum) {
        db = databaseHelper.getReadableDatabase();
        String sql = "select _Id from t_share where sharenum=''" + shareNum + "''";
        int Id = -1;
        Cursor cursor = db.rawQuery(sql, null);
        if (cursor != null) {
            while (cursor.moveToNext()){
                Id = cursor.getInt(0);
            }
        cursor.close();
        return Id;
    public List<ShareBean> getShareList(){
        List<ShareBean> shareBeans = new ArrayList<>();
        String sql = "select _id,sharenum,sharename,shareprice,sharelastprice,uptime,addtime,bl from t_share order by _Id desc";
                ShareBean shareBean = new ShareBean();
                shareBean.set_Id(cursor.getInt(0));
                shareBean.setShareNum(cursor.getString(1));
                shareBean.setShareName(cursor.getString(2));
                shareBean.setSharePrice(cursor.getDouble(3));
                shareBean.setShareLastPrice(cursor.getDouble(4));
                shareBean.setUptime(cursor.getString(5));
                shareBean.setAddtime(cursor.getString(6));
                shareBean.setBl(cursor.getDouble(7));
                shareBeans.add(shareBean);
        return shareBeans;
    public List<ShareHisBean> getShareListHis(int ShareId){
        List<ShareHisBean> shareHisBeans = new ArrayList<>();
        String sql = "select _id,shareid,shareprice,uptime from t_sharehis where shareid=''"+String.valueOf(ShareId)+"'' order by _id desc";
                ShareHisBean shareHisBean = new ShareHisBean();
                shareHisBean.set_Id(cursor.getInt(0));
                shareHisBean.setShareId(cursor.getInt(1));
                shareHisBean.setSharePrice(cursor.getDouble(2));
                shareHisBean.setUpTime(cursor.getString(3));
                shareHisBeans.add(shareHisBean);
        return shareHisBeans;
    public ShareBean getShareInfo(int ShareId) {
        ShareBean shareBean = new ShareBean();
        //_id integer primary key autoincrement,sharenum text,sharename text,shareprice real,sharelastprice real,addtime text,uptime text,bl real
        String sql = "select _id,sharenum,sharename,shareprice,sharelastprice,addtime,uptime,bl from t_share where _Id=''"+String.valueOf(ShareId)+"''";
            if (cursor.moveToNext()){
                shareBean.setAddtime(cursor.getString(5));
                shareBean.setUptime(cursor.getString(6));
        return shareBean;
}

3、实际中的应用,就举一个例子吧,数据库操作不用开新线程,直接在主线程里弄就行

ShareDbService shareDbService = new ShareDbService(getContext());
 shareDbService.delShare(String.valueOf(shareBean.get_Id()));

4、需要注意的是SQLite不支持多线程,最好是能批量修改,否则很麻烦,如果一定要多线程 ,比如循环请求网络更新数据库时,可以使用CountDownLatch,先将数据弄在一个集合里,等子线程全部执行完成后,再更新数据库。此方法具体应用如下

先声明一个变量

CountDownLatch latch;

实际应用代码

//设置多线程 个数,一共用多少个线程一定要写清楚,后面是要减的。
        latch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {            
            new Thread(()-> {
                try {
                    //网络请求等操作
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    //这里会自动减1操作,一定要写。
                    latch.countDown();
                }
            }).start();
        };
        try {
            latch.await();
           //最后执行主程序,比如更新数据库
            Toast.makeText(getContext(), "刷新成功", Toast.LENGTH_SHORT).show();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

到此这篇关于Android在Sqlite3中的应用及多线程使用数据库的建议的文章就介绍到这了,更多相关android Sqlite3多线程内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

您可能感兴趣的文章:
  • Android性能优化之plt hook与native线程监控详解
  • Android Dispatchers.IO线程池深入刨析
  • Android 线程优化知识点学习
  • android原生实现多线程断点续传功能
  • Android实现多线程断点续传
  • Android性能优化之线程监控与线程统一详解

Django:使用sqlite3作为数据库在Heroku上部署应用程序

Django:使用sqlite3作为数据库在Heroku上部署应用程序

我想将带有sqlite3的应用程序部署为Heroku上的数据库。但是,似乎Heroku不支持将sqlite3作为数据库的应用程序。是真的吗
无法在Heroku上部署由sqlite3支持的应用程序吗?

PS:我已经使用PythonAnywhere成功部署了我的应用程序,但是现在想知道是否有使用Heroku部署它的任何可能方法。

iphone – iOS应用程序sqlite3上的脱机缓存已损坏

iphone – iOS应用程序sqlite3上的脱机缓存已损坏

我有一个iOs应用程序的sqlite3数据库,以便为系统提供离线支持.

它完美地运作.但有时.db文件已损坏.而且不会返回结果.

如果我通过命令行检查SELECT指令,我会收到下一条错误消息:

sqllite Error: database disk image is malformed

虽然不可取,但它会变得腐败.数据库只是一个辅助系统,足以能够从iOS应用程序检测到文件已损坏并重新启动文件.

但是使用sqlite3语句我没有得到任何异常.代码如下:

sqlRaw = @"SELECT ... ";
const char *sql = [sqlRaw cStringUsingEncoding:NSUTF8StringEncoding];
if (sqlite3_prepare_v2(database,sql,-1,&date_statement,NULL) != sqlITE_OK) {
    NSAssert1(0,@"Error: Failed to prepare statement with message '%s'.",sqlite3_errmsg(database));
}

NSMutableArray *entities = [[NSMutableArray alloc] initWithCapacity:0];
while (sqlite3_step(date_statement) == sqlITE_ROW) {
    NSData *entityXml = [[NSData alloc] initWithBytes:sqlite3_column_blob(date_statement,0) 
                                                   length:sqlite3_column_bytes(date_statement,0)];
    [entities addobject:entityXml];
}
sqlite3_finalize(date_statement);

当应用程序执行前面的代码时,只返回一个空数组,不会抛出任何异常.

有谁知道如何从sqlite3语句检查.db文件状态?

也许用户其他存储系统更好.有什么建议?

解决方法

最后,我决定从应用程序检查数据库状态,如果数据库已损坏,则只需替换新的空数据库.

- (BOOL) isDatabaseCorrupted {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    Nsstring *documentsDirectory = [paths objectAtIndex:0];
    Nsstring *path = [documentsDirectory stringByAppendingPathComponent:cache_final_path];
    BOOL bResult = FALSE;
    if (sqlite3_open([path UTF8String],&database) == sqlITE_OK) {  
        @try {
            Nsstring *sqlRaw = @"PRAGMA integrity_check;";
            const char *sql = [sqlRaw cStringUsingEncoding:NSUTF8StringEncoding];
            if (sqlite3_prepare_v2(database,&check_statement,NULL) == sqlITE_OK) {
                int success = sqlite3_step(check_statement);
                NSLog(@"sql integrity_check result is %d",success);
                Nsstring *response = nil;
                switch (success) {
                    case sqlITE_ERROR:
                        bResult = TRUE;
                        break;
                    case sqlITE_DONE:
                        NSLog(@"Result is simple DONE of the sqllite3 on isDatabaseCorrupted");
                        break;
                    case sqlITE_BUSY:
                        NSLog(@"Result is simple BUSY of the sqllite3 on isDatabaseCorrupted");
                        break;
                    case sqlITE_MISUSE:
                        NSLog(@"Bad utilization of the sqllite3 on isDatabaseCorrupted");
                        break;
                    case sqlITE_ROW:
                        response = [Nsstring stringWithUTF8String:(char *)sqlite3_column_text(check_statement,0)];
                        if ([[[response lowercaseString] stringByTrimmingCharactersInSet:[NSCharacterSet 
                                                                                          whitespaceAndNewlineCharacterSet]] 
                             isEqualToString:@"ok"]){
                            bResult = FALSE;
                        } else {
                            NSLog(@"ATTENTION: integrity_check response %@",response);
                            bResult = TRUE;
                        }
                        break;
                    default:
                        break;
                }

                sqlite3_finalize(check_statement);
            }

        }
        @catch (NSException *exception) {
            [TSLogger log:[Nsstring stringWithFormat:@"Exception %@",[exception description]] 
             withSeverity:severity_error];
            return TRUE;
        }        
    }

    sqlite3_close(database);
    return bResult;
}

结果是按照sqlite3文档的预期响应顺序定义的.

谢谢,

伊万

今天关于Sqlite3.0数据库在iPhone中的应用的讲解已经结束,谢谢您的阅读,如果想了解更多关于Android在Sqlite3中的应用及多线程使用数据库的建议、Android在Sqlite3中的应用及多线程使用数据库的建议(实例代码)、Django:使用sqlite3作为数据库在Heroku上部署应用程序、iphone – iOS应用程序sqlite3上的脱机缓存已损坏的相关知识,请在本站搜索。

本文标签: