读取数据库首先要得到数据库的位置,在编译的时候数据库的位置位于assets目录中的。但在安装调试APP时,数据库就会被放到data/data/com.example.administrator目录中,数据库的名称为assets目录中的名称。如test.db。
首先读取数据库的数据就先得到数据库:
/** * 这个类就是实现从assets目录读取数据库文件然后写入SDcard中,如果在SDcard中存在,就打开数据库,不存在就从assets目录下复制过去 * @author Big_Adamapple * */ public class SQLDB { //数据库存储路径 String DBPATH = "/data/data/com.example.administrator.musicplayer"; String dbName=null; public SQLDB(String dbName) { this.dbName=dbName; } SQLiteDatabase db; public SQLiteDatabase openDatabase(Context context){ File jhPath=new File(DBPATH+"/"+dbName); //查看数据库文件是否存在 if(jhPath.exists()){ Log.i("test", "存在数据库"+jhPath); //存在则直接返回打开的数据库 return SQLiteDatabase.openOrCreateDatabase(jhPath, null); }else{ //不存在先创建文件夹 File path=new File(DBPATH); Log.i("test", "DBPATH="+path); if (path.mkdir()){ Log.i("test", "创建成功"); }else{ Log.i("test", "创建失败"); }; try { //得到资源 AssetManager am= context.getAssets(); //得到数据库的输入流 InputStream is=am.open(dbName); Log.i("test", is+""); //用输出流写到SDcard上面 FileOutputStream fos=new FileOutputStream(jhPath); Log.i("test", "fos="+fos); Log.i("test", "jhPath="+jhPath); //创建byte数组 用于1KB写一次 byte[] buffer=new byte[1024]; int count = 0; while((count = is.read(buffer))>0){ Log.i("test", "得到"); fos.write(buffer,0,count); } //最后关闭就可以了 fos.flush(); fos.close(); is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } //如果没有这个数据库 我们已经把他写到SD卡上了,然后在执行一次这个方法 就可以返回数据库了 return openDatabase(context); } } }
如果报错的:unknown error (code 14): Could not open database就将路径改为
String DBPATH = Environment.getExternalStorageDirectory().getAbsolutePath()+"/com.example.administrator.musicplayer";
然后对数据库进行查询得到cursor:
SQLDB s=new SQLDB("NKCityCode.db");SQLiteDatabase db =s.openDatabase(getApplicationContext());//查询数据库中province_code不为空的数据Cursor cursor=db.query("carnumber_province", new String[]{"shortname","province_code","id"},null,null,"province_code","province_code != \"\"",null,null);
查询后要得到相应的数据:
这里可能会出现报错String province_code = null; String shortname=null; String id=null; if (cursor.moveToFirst()){ while (cursor.moveToNext()){ Map<String,String> itemMap = new HashMap<String,String>(); id = cursor.getString(cursor.getColumnIndex("id")); shortname = cursor.getString(cursor.getColumnIndex("shortname")); province_code= cursor.getString(cursor.getColumnIndex("province_code")); provinceShortname.add(shortname); itemMap.put(shortname,id); provinceId.add(itemMap); } Log.i("ggg", "data: "+provinceId); } cursor.close();
Couldn't read row 1, col -1 from CursorWindow. Make sure the Cursor is initi...
这里报错是因为cursor.getString(cursor.getColumnIndex("id"))中的cursor.getColumnIndex("id")的值为负数。
而出现报错的原因就是要得到的值在得到cursor的查询语句中没有相应字段。如
Cursor cursor=db.query("carnumber_province", new String[]{"shortname","province_code"},null,null,"province_code","province_code != \"\"",null,null);没有id字段时,想查询id的字段就会出现上述报错。也有可能是你在拼写字段名称时出现错误或者空格等。