标签:getDatabasePath Sqlite name 数据库 db fileName contentValues new Android
一.把数据库文件如"citys.db",放到assets目录下,再把这个文件拷贝到数据库对应的目录.代码如下:
if(!getDatabasePath(fileName).exists())//先判断文件是否存在,filename即"citys.db"
{
try
{
InputStream inStream = this.getAssets().open(fileName);
File file = new File(getDatabasePath(fileName).toString().substring(0, getDatabasePath(fileName).toString().indexOf(fileName)));
if(!file.exists()) file.mkdir();//如果目录不存在,则先创建目录
OutputStream outStream = new FileOutputStream(getDatabasePath(fileName).toString());
byte[] buffer = new byte[1024];
int length = 0;
while((length = inStream.read(buffer)) > 0)
{
outStream.write(buffer, 0, length);
}
outStream.flush();
outStream.close();
inStream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
二.打开数据库
方法一:
//getDatabasePath(fileName).toString()即/data/data/getPackageName()/databases/fileName
//此方法打开的数据库必须要先创建好表android_metadata,否则会报错:
sqlite returned: error code = 1, msg = no such table: android_metadata
SQLiteDatabase db = SQLiteDatabase.openDatabase(getDatabasePath(fileName).toString(), null, SQLiteDatabase.OPEN_READONLY);
方法二:
//此方法会在没有这个数据库时自动创建
SQLiteDatabase db = this.openOrCreateDatabase(fileName, MODE_PRIVATE, null);
三.创建表
db.execSQL("create table if not exists cities(" + "id INTEGER PRIMARY KEY," + "city_name TEXT," + "longitude INTERGER," + "latitude INTERGER," + "province_name TEXT" + ");"); //如果没有citise这个表就创建这个表
四.查询表
Cursor cursor = db.query("cities", new String[]{"city_name","longitude","latitude"}, "province_name==?", new String[]{"湖南"}, null, null, null);//"cities"为表名
while(cursor.moveToNext())
{
String name =cursor.getString(cursor.getColumnIndex("city_name"));
System.out.println(name);
}
五.插入数据
ContentValues contentValues = new ContentValues();
contentValues.put("id", 1);
contentValues.put("city_name", "常德");
contentValues.put("longitude", 113650001);
contentValues.put("latitude", 34720001);
contentValues.put("province_name", "湖南");
db.insert("cities", null, contentValues);
六.清空数据
db.execSQL("drop table if exists cities;");
七.关闭数据库
cursor.close();
db.close();
标签:getDatabasePath,Sqlite,name,数据库,db,fileName,contentValues,new,Android 来源: https://blog.51cto.com/u_15298588/3034417
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。