目录
0、相关文章:
http://www.it1352.com/161373.html
1、正文
问题描述:通过一下sql语句,希望根据当前的经纬度查询方圆五公里内的需要打点的所有坐标点的经纬度
String sql = "SELECT * , (6371 * ACOS ( cos ( radians ( " + latitude +
" ) ) * cos( radians(lat) ) * cos( radians(lon) - radians( " + longitude +
" ) ) + sin( radians( " + longitude
+ " ) ) * sin( radians(lat) ) ) )" +
"AS distance " +
"FROM " + Constant.TABLE_RDD_IMAGES +
" HAVING distance < 1 " +
"ORDER BY distance " +
"LIMIT 1";
但是却报错:
2、原因:
SQLite不支持任何默认三角函数,所以你不能在SQL查询中使用它们。
3、解决方案:
https://stackoverflow.com/questions/7867099/how-can-i-create-a-user-defined-function-in-sqlite
SQLite does not have support for user-defined functions in the way that Oracle or MS SQL Server does.
For SQLite, you must create a callback function in C/C++ and hook the function up using the sqlite3_create_function call.
Unfortunately, the SQLite API for Android does not allow for the sqlite3_create_function
call directly through Java. In order to get it to work you will need to compile the SQLite C library with the NDK.
And if you are still interested read 2.3 User-defined functions...
Here's how to create a function that finds the first byte of a string.
static void firstchar(sqlite3_context *context, int argc, sqlite3_value **argv)
{
if (argc == 1) {
char *text = sqlite3_value_text(argv[0]);
if (text && text[0]) {
char result[2];
result[0] = text[0]; result[1] = '\0';
sqlite3_result_text(context, result, -1, SQLITE_TRANSIENT);
return;
}
}
sqlite3_result_null(context);
}
Then attach the function to the database.
sqlite3_create_function(db, "firstchar", 1, SQLITE_UTF8, NULL, &firstchar, NULL, NULL)
Finally, use the function in a sql statement.
SELECT firstchar(textfield) from table
做一个简单翻译:
SQLite不像Oracle或MS SQL Server那样支持用户定义函数。对于SQLite,必须在C/C++中创建回调函数,并使用sqlite3_create_function函数调用来hook函数。
不幸的是,用于Android的SQLite API不允许直接通过Java调用sqlite3_create_函数。为了让它工作,您需要用NDK编译SQLite C库。
如果你仍然感兴趣,请阅读2.3用户定义函数。。。
下面是如何创建一个函数来查找字符串的第一个字节。
static void firstchar(sqlite3_context *context, int argc, sqlite3_value **argv)
{
if (argc == 1) {
char *text = sqlite3_value_text(argv[0]);
if (text && text[0]) {
char result[2];
result[0] = text[0]; result[1] = '\0';
sqlite3_result_text(context, result, -1, SQLITE_TRANSIENT);
return;
}
}
sqlite3_result_null(context);
}
然后将函数添加到数据库。
sqlite3_create_function(db, "firstchar", 1, SQLITE_UTF8, NULL, &firstchar, NULL, NULL)
最后,在sql语句中使用该函数。
SELECT firstchar(textfield) from table