将db文件放在res的raw路径(可以自己添加这个路径)下面,要打开它的时候这样:
private String filename = DB_PATH+"/"+DB_NAME
DB_PATH我是这样定义的:
public static final String DB_PATH = "/data"+Environment.getDataDirectory().getAbsolutePath()
+"/"+PACKAGE_NAME
DB_NAME肯定就是你数据库的名字啦。
public void open()throws SQLException
{
writefromraw(filename)
db = opendatabase()
}
private void writefromraw(String dbfile) {
// TODO Auto-generated method stub
try {
if (!(new File(dbfile).exists())) {
InputStream is = mContext.getResources().openRawResource(
R.raw.livetv_database)
FileOutputStream fos = new FileOutputStream(dbfile)
byte[] buffer = new byte[BUFFER_SIZE]
int count = 0
while ((count = is.read(buffer)) >0) {
fos.write(buffer, 0, count)
}
fos.close()
is.close()
}
} catch (FileNotFoundException e) {
Log.e("Database", "File not found")
e.printStackTrace()
} catch (IOException e) {
Log.e("Database", "IO exception")
e.printStackTrace()
}
}
下载一个Linux 的sqlite3工具(或到SqLite网站下载sqlite的源代码,在你的系统中编译出sqlite3工具),用这个工具打开:sqlite3 /tmp/test.db
通过while语句逐条读取,这是我项目里的部分源码,自己理解一下,希望能帮到你。-(BOOL)databaseTest{//数据库 *** 作NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)NSString*documentsDirectory=[pathsobjectAtIndex:0]NSString*path=[documentsDirectorystringByAppendingPathComponent:@"mydb.db"]//查找db文件返回其pathNSLog(path)//打印db文件的路径NSFileManager*fileManager=[NSFileManagerdefaultManager]BOOLfind=[fileManagerfileExistsAtPath:path]if(find){NSLog(@"Sucess:finddnfile.")if(sqlite3_open([pathUTF8String],&database_)==SQLITE_OK)//打开数据库{//打开数据库成功NSLog(@"Sucess:opendatabasesucess.")///////////////////////////////////////////////////////////////////////////////////这里进行数据库 *** 作///////////////////////////////////////////////////////////////////////////////////////////////////////////1.插入数据//////////////////////////////////////////////////SQL查询语句char*sql="INSERTINTOstudents(name)VALUES(?)"//会话sqlite3_stmt*statement//调制一个会话intsuccess=sqlite3_prepare_v2(database_,sql,-1,&statement,NULL)if(success!=SQLITE_OK){NSLog(@"Error:failedtoinsert:channels")}//绑定数据sqlite3_bind_text(statement,1,"Kevin",-1,SQLITE_TRANSIENT)//注意此处的字符串为旧字符串success=sqlite3_step(statement)sqlite3_finalize(statement)if(success==SQLITE_ERROR){NSLog(@"Error:failedtoinsertintothedatabasewithmessage.")}//2.查询数据statement=nilchar*sql_select="SELECTnameFROMstudents"if(sqlite3_prepare_v2(database_,sql_select,-1,&statement,NULL)!=SQLITE_OK){NSLog(@"Error:failedtopreparestatementwithmessage:getchannels.")}//查询结果集中一条一条的遍历所有的记录,这里的数字对应的是列值。while(sqlite3_step(statement)==SQLITE_ROW){char*name=(char*)sqlite3_column_text(statement,0)//第一列数据,注意此处师从0开始的NSString*nameNs=[[NSStringalloc]initWithUTF8String:name]NSLog(nameNs)[nameNsrelease]}sqlite3_finalize(statement)//关闭数据库sqlite3_close(database_)returnYES}else{sqlite3_close(database_)NSLog(@"Error:opendatabasefile.")returnNO}returnNO}欢迎分享,转载请注明来源:内存溢出
评论列表(0条)