读取外部的SQLdatabase步骤

//1:首先要将后缀为db的文件放入工程的资源中res下的raw文件夹



//2:外部数据库需要我们先存入手机内存,然后再打开,所以我们要开读写权限


//代码部分:

String permissons[] = {android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
String   SdPath = Environment.getExternalStorageDirectory().getPath();

//在oncreate中先申请权限

if (hasPermission(permissons)) {
} else {
    hasRequse(1, permissons);
}

public boolean hasPermission(String... permission) {
    for (String permissiom : permission) {
        if (ActivityCompat.checkSelfPermission(this, permissiom) != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
    }
    return true;
}

public void hasRequse(int code, String... permission) {
    ActivityCompat.requestPermissions(this, permission,code);
}
 
//3:解读数据,首先将资源文件存入SD卡,然后再从SD卡中打开数据库
    private void initCity() {
		//打开资源文件获取输入流
        InputStream in = getResources().openRawResource(R.raw.city);
		//存入SD卡之前一定要先创建路径
        File file = new File(SdPath + "//sql_database//");
        file.mkdirs();
		//创建要写入的文件对象
        File file1=new File(file.getPath(),"city.db");
        try {
            FileOutputStream out = new FileOutputStream(file1);
            byte b[] = new byte[1024];            
                while (in.read(b) != -1) {
                    out.write(b);
		}              
                in.close();
                out.flush();
                out.close();
        } catch (IOException e) {
            e.printStackTrace();            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        db = openOrCreateDatabase(file1.getPath(), Context.MODE_PRIVATE, null);
        Cursor cursor = db.rawQuery(" select * from t_city ", null);
        Log.i(TAG, "cursor.getCount() === " + cursor.getCount());
    }
//得到了cursor 您就可以为所欲为了。附件demo:链接:http://pan.baidu.com/s/1bYNiEy 密码:9o19
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值