标签:
工作需要使用数据库进行大量的插入工作,故此想通过使用c进行这部分工作,经过查资料,发现一篇文章比较实用:
方法1.使用源码sqlite3.h,sqlite3.c进行编译。
方法2.使用android编译好得到得libsqlite.so库
具体方法:
1) 使用adb命令 adb pull /system/lib/libsqlite.so 得到libsqlite.so库(在当前用户的根目录下)。
2)把得到libsqlite.so拷贝到$NDK/platforms/android-3/arch-arm/usr/lib 目录下(建议拷贝到platforms所有子目录的相应位置)
3)把sqlite3.h头文件拷贝到$NDK/platforms/android-3/arch-arm/usr/include目录下(同上),头文件可再在此下载
4)在android.mk文件中加入语句 LOCAL_LDLIBS := -lsqlite (注意如果需要链接编译多个动态库时,在该语句后面接这加动态库如:LOCAL_LDLIBS := -lsqlite -llog)
5)以下使用代码:
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "native-activity", __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "native-activity", __VA_ARGS__))
extern "C" {
JNIEXPORT
void JNICALL
Java_com_sinde_nativedb_NativeDBHelper_insertWithTableName(JNIEnv*
env,jobject obj,jstring dbPath,jstring f ilePath,jstring
tableName);
}
JNIEXPORT
void JNICALL
Java_com_sinde_nativedb_NativeDBHelper_insertWithTableName(JNIEnv*
env,jobject obj,jstring dbPath,jstring filePath,jstring tableName){
sqlite3 *db;
char *pErrMsg = 0;
char* dbP = jstringTostring(env,dbPath);
char* fP = jstringTostring(env,filePath);
char* tName = jstringTostring(env,tableName);
int openState = sqlite3_open(dbP,&db);
if(openState != SQLITE_OK){
return;
}
FILE *f;
if((f = fopen(fP,"r")) == NULL){
return;
}
char line[4096];
char sql[6134];
char head[1024];
memset(line,0,4096);
memset(sql,0,6134);
memset(head,0,1024);
readLine(f,head);
LOGW("line:%s",head);
int size = 0;
while(!feof(f)){
readLine(f,line);
sprintf(sql,"insert into %s (%s) values (%s)",tName,head,line);
if(size==0){
sqlite3_exec(db, "BEGIN;", 0, 0, &pErrMsg);
}
// LOGW("sql:%s",sql);
sqlite3_exec(db,sql,0,0,&pErrMsg);
if(size == 5000){
size = 0;
sqlite3_exec(db, "COMMIT;", 0, 0, &pErrMsg);
LOGW("insert 5000");
}else{
size++;
}
memset(line,0,4096);
memset(sql,0,6134);
sqlite3_free(pErrMsg);
}
if(size != 0){
sqlite3_exec(db, "COMMIT;", 0, 0, &pErrMsg);
sqlite3_free(pErrMsg);
}
LOGW("insert over");
fclose(f);
sqlite3_close(db);
}
//读文件的一行
char* readLine(FILE* f,char* line){
char* start = line;
char temp;
while(((temp = fgetc(f)) != ‘\n‘) && !feof(f)){
*start++ = temp;
}
return line;
}
//jstring转char*
char* jstringTostring(JNIEnv* env, jstring jstr)
{
char* rtn = NULL;
jclass clsstring = env->FindClass("java/lang/String");
jstring strencode = env->NewStringUTF("utf-8");
jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");
jbyteArray barr= (jbyteArray)env->CallObjectMethod(jstr, mid, strencode);
jsize alen = env->GetArrayLength(barr);
jbyte* ba = env->GetByteArrayElements(barr, JNI_FALSE);
if (alen > 0)
{
rtn = (char*)malloc(alen + 1);
memcpy(rtn, ba, alen);
rtn[alen] = 0;
}
env->ReleaseByteArrayElements(barr, ba, 0);
return rtn;
}
标签:
原文地址:http://www.cnblogs.com/sinde/p/4604982.html