query_result *sqlite_db::exec_sql(const std::string& sql){ query_result *result_set=NULL; // std::cout<<sql<<std::endl; result_set=new query_result(); if(sqlite3_exec(sqlite, sql.c_str(), sqlite_db::fptr_store_row_data, result_set, NULL)!=SQLITE_OK){ throw sql_execution_error(); } if(result_set->nr_of_result_rows()==0){ delete result_set; result_set=NULL; } return result_set; }
query_result *jni_db::exec_sql(const std::string& sql){ query_result *result=NULL; std::string row_index; field field; char **fields=NULL; jstring jsql=env->NewStringUTF(sql.c_str()); jobjectArray raw_sqlite_result=reinterpret_cast<jobjectArray>(env->CallObjectMethod(dbhelperobj,dbhelper_exec_sql,jsql)); if(env->ExceptionCheck()==JNI_TRUE){ env->ExceptionClear(); throw sql_execution_error(); } env->ReleaseStringUTFChars(jsql,env->GetStringUTFChars(jsql,NULL)); env->DeleteLocalRef(jsql); if(raw_sqlite_result!=NULL){ jsize raw_sqlite_result_size=env->GetArrayLength(raw_sqlite_result); result=new query_result(); jobjectArray column_names=reinterpret_cast<jobjectArray>(env->CallObjectMethod(dbhelperobj,dbhelper_get_metadata)); jsize column_names_size=env->GetArrayLength(column_names); if(column_names_size>0){ fields=new char*[column_names_size]; for(jsize i=0;i<column_names_size;++i){ jobject column_name_jobj=env->GetObjectArrayElement(column_names,i); jstring column_name=reinterpret_cast<jstring>(column_name_jobj); std::string colname=jstring2string(column_name); env->DeleteLocalRef(column_name_jobj); logger::singleton()==NULL?(void)0:logger::singleton()->log(3,"execsql:"+colname); fields[i]=new char[colname.length()+1]; fields[i][colname.length()]='\0'; colname.copy(fields[i],colname.length()); } unsigned int nr_of_columns=column_names_size; result->set_metadata(nr_of_columns,(const char**) &(*fields)); } env->DeleteLocalRef(column_names); unsigned char row_struct_counter=0; for(jsize i=0;i<raw_sqlite_result_size;++i){ if(row_struct_counter==0){ jobject rowid_jobj=env->GetObjectArrayElement(raw_sqlite_result,i); jstring rowid=reinterpret_cast<jstring>(rowid_jobj); row_index=jstring2string(rowid); env->DeleteLocalRef(rowid_jobj); row_struct_counter=1; } else if(row_struct_counter==1){ jobject column_name_jobj=env->GetObjectArrayElement(raw_sqlite_result,i); jstring column_name=reinterpret_cast<jstring>(column_name_jobj); field.field_name=jstring2string(column_name); env->DeleteLocalRef(column_name_jobj); row_struct_counter=2; } else if(row_struct_counter==2){ jobject column_value_jobj=env->GetObjectArrayElement(raw_sqlite_result,i); jstring column_value=reinterpret_cast<jstring>(column_value_jobj); field.field_value=jstring2string(column_value); env->DeleteLocalRef(column_value_jobj); result->insert(std::make_pair(std::atoi(row_index.c_str()),field)); row_struct_counter=0; } } env->DeleteLocalRef(raw_sqlite_result); } return result; }