当我尝试将它用于select时,我的sqlite3_bind_text函数有问题.
目的是在我的数据的10分钟时间段内获得最新值.
如果我使用预准备语句并绑定我的值,则与使用SQL语法的普通字符串相比,结果会有所不同.
两个测试的SQL语法’应该’是相同的.
当代码运行时,我得到以下输出:
test 1 = 0.000000 AnalogRPM <-- Error
test 2 = 7.700000 7.69999980926514 <-- Correct value
在我看来,我的绑定语句返回列的名称而不是值(就像将值插入’AnalogRPM’一样
你们有没有经历过类似的事情?或者你能在我的代码中看到任何错误吗?
任何反馈意见:)
char str[1000];
sqlite3_stmt *test1;
/** First test, use prepared statement to get double value */
snprintf(str, sizeof(str),
"select ? from DATA WHERE ts_sec BETWEEN ? AND ? ORDER BY rowid DESC LIMIT 1");
/** All 'rc' are check in my code, i just left them out to make it easier to read */
rc = sqlite3_prepare_v2(db_livedata, str, -1, &test1, 0);
if(rc != SQLITE_OK)
printf("SQL error on line:%d msg:%s \n",__LINE__, sqlite3_errmsg(db_livedata));
rc = sqlite3_bind_text( test1, 1, "AnalogRPM",-1,0);
rc = sqlite3_bind_int( test1, 2, stat_time.tv_sec - 600);
rc = sqlite3_bind_int( test1, 3, stat_time.tv_sec);
do
{
rc = sqlite3_step( test1);
switch( rc )
{
/** No more data */
case SQLITE_DONE:
break;
/** New data */
case SQLITE_ROW:
{
uint16_t size = sqlite3_column_count( test1);
if(size == 1) // should always be one
{
value = sqlite3_column_double( test1, 0);
printf("test 1 = %f %s\n",value, sqlite3_column_text(test1, 0));
}
}
break;
default:
break;
}
}while( rc==SQLITE_ROW );
/** Second test use normal string for prepare */
sqlite3_stmt *test2;
snprintf(str, sizeof(str),
"select AnalogRPM from DATA WHERE ts_sec BETWEEN %d AND %d ORDER BY rowid DESC LIMIT 1"
,stat_time.tv_sec - 600, stat_time.tv_sec);
rc = sqlite3_prepare_v2(db_livedata, str, -1, &test2, 0);
if(rc != SQLITE_OK)
printf("SQL error on line:%d msg:%s \n",__LINE__, sqlite3_errmsg(db_livedata));
do
{
rc = sqlite3_step( test2);
switch( rc )
{
/** No more data */
case SQLITE_DONE:
break;
/** New data */
case SQLITE_ROW:
{
uint16_t size = sqlite3_column_count( test2);
if(size == 1)
{
value = sqlite3_column_double( test2, 0);
printf("test 2 = %f %s\n",value, sqlite3_column_text(test2, 0));
}
}
break;
default:
break;
}
}while( rc==SQLITE_ROW );
最佳答案 第一个版本基本上是
SELECT 'AnalogRPM' ...
而第二个是
SELECT AnalogRPM ...
区别在于表达式是字符串文字或列名.
您不能对列名使用变量绑定.需要在SQL语句编译时知道列名.