Iam遇到一个问题,其中预准备语句和绑定值适用于插入语句但不适用于选择语句.... 这是一段代码
int main(int argc, CHAR* argv[])
{
sqlite3 *db; // sqlite3 db struct
char *zErrMsg = 0;
char *szSQL;
int rc;
// Open the test.db file
rc = sqlite3_open("test32.db", &db);
if( rc )
{
// failed
fprintf(stderr, "Can't open database: %s\n",
sqlite3_errmsg(db));
}
else
{
// success
fprintf(stderr, "Open database successfully\n");
}
// create myTable
//szSQL = "create table myTable1011 (FirstName varchar(30), LastName varchar(30), Age smallint not null);";
// rc = sqlite3_exec(db, szSQL, callback, 0, &zErrMsg);
// if( rc == SQLITE_OK )
// {
//insert 1 record into myTable
// RunInsertParamSQL(db, "asyb", "com", 42);
// fetch records
sqlite3_stmt *stmt;
const char *pzTest;
//Doesnt WORK
szSQL = "select * from myTable1011 where age = ?";
rc = sqlite3_prepare_v2(db, szSQL, strlen(szSQL), &stmt, &pzTest);
if( rc == SQLITE_OK )
// bind the value
int test = 42;
sqlite3_bind_int(stmt, 1, test);//Doesnt work if i give 42 directly instead if test in bind statement
// commit
sqlite3_step(stmt);
sqlite3_finalize(stmt);
}
// rc = sqlite3_exec(db, szSQL, callback, 0, &zErrMsg);
// Close test.db file
sqlite3_close(db);
getchar();
return 0;
}
// Insert rec
//WORKS WELL
void RunInsertParamSQL(sqlite3 *db, char *fn, char *ln, int age)
{
if (!db)
return;
char *zErrMsg = 0;
sqlite3_stmt *stmt;
const char *pzTest;
char *szSQL;
// Insert data item into myTable
szSQL = "insert into myTable1011 (FirstName, LastName, Age) values (?,?,?);";
int rc = sqlite3_prepare(db, szSQL, strlen(szSQL), &stmt, &pzTest);
if( rc == SQLITE_OK ) {
// bind the value
sqlite3_bind_text(stmt, 1, fn, strlen(fn), 0);
sqlite3_bind_text(stmt, 2, ln, strlen(ln), 0);
sqlite3_bind_int(stmt, 3, age);
// commit
sqlite3_step(stmt);
sqlite3_finalize(stmt);
}
}
除了成功打开数据库之外我没有输出
但是,如果我给 szSQL =“select * from myTable1011”; rc = sqlite3_exec(db,szSQL,callback,0,& zErrMsg); //我得到了整张桌子......
我如何有选择地打印? 为什么我的Where Condition失败?????
答案 0 :(得分:0)
没有输出,因为代码甚至没有尝试输出任何内容。
您必须使用sqlite3_column_* functions:
读取列值...
for (;;) {
rc = sqlite3_step(stmt);
if (rc != SQLITE_ROW)
break;
// this depends on what columns you actually have:
int first_column = sqlite3_column_int (stmt, 0);
const char *second_column = sqlite3_column_text(stmt, 1);
...
printf("ID: %d, name: %s\n", first_column, second_column);
}
if (rc != SQLITE_DONE)
printf("error: %s\n", sqlite3_errmsg(db));
sqlite3_finalize(stmt);
...
答案 1 :(得分:0)
最后我明白了......
如果您使用Sprintf而不是准备/绑定语句,我可以获得输出....
sprintf(szSQL,"select * from Foldersonly WHERE Foldersonly.FolderName = \"%s\" ",Root_Path);
sqlite3_exec(db, szSQL, callback, 0, &zErrMsg);
这将有效...