I'm starting from the bottom-up to learn iPad development after 15 years with Cold Fusion. I'm getting comfortable with Ansi C and xCode, but am stumped taking the next step with SQLite.
I've built a database (Airports.sqlite) with razorSQL and installed it in the same directory as main.c where I've also installed the amalgamated sqlite3.h and sqlite3.h files.
Everything compiles OK, but I get the following message when I Run...
Error in select statement select Length from Runways order by Length desc limit 5 [no such table: Runways].
The database definitely has the Runways table in it. Can someone set me straight? Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sqlite3.h"
#include "weightbalance.h"
sqlite3* db;
int first_row;
int select_callback(void *p_data, int num_fields, char **p_fields, char **p_col_names) {
int i;
int *p_rn = (int*)p_data;
if (first_row) {
first_row = 0;
for(i=0; i < num_fields; i++) {
printf("%20s", p_col_names[i]);
}
printf("\n");
for(i=0; i< num_fields*20; i++) {
printf("=");
}
printf("\n");
}
(*p_rn)++;
for(i=0; i < num_fields; i++) {
printf("%20s", p_fields[i]);
}
printf("\n");
return 0;
}
void select_stmt(const char* stmt) {
char *errmsg;
int ret;
int nrecs = 0;
first_row = 1;
ret = sqlite3_exec(db, stmt, select_callback, &nrecs, &errmsg);
开发者_如何学运维 if(ret!=SQLITE_OK) {
printf("Error in select statement %s [%s].\n", stmt, errmsg);
}
else {
printf("\n %d records returned.\n", nrecs);
}
}
void sql_stmt(const char* stmt) {
char *errmsg;
int ret;
ret = sqlite3_exec(db, stmt, 0, 0, &errmsg);
if(ret != SQLITE_OK) {
printf("Error in statement: %s [%s].\n", stmt, errmsg);
}
}
int main() {
sqlite3_open("Airports.sqlite", &db);
if(db == 0) {
printf("Could not open database.");
return 1;
}
printf("\nSelecting Airports with the longest runways.\n\n");
select_stmt("select Length from Runways order by Length desc limit 5");
sqlite3_close(db);
return 0;
}
Most likely, the file "Airports.sqlite" opened in main() is not the one you think it is. Without path information, sqlite3_open() will just open the file in the current working directory.
As a debug step, add "printf(getwd(NULL))" just before your sqlite3_open() statement. Then you'll know whether you're opening your existing database or just creating a new, empty one that is missing your table.
Also, since you're using Xcode, you can just pass the path to your database as a command-line parameter (argv). In Xcode 4, choose Product->Edit Scheme. In the "run" section, add the path to "Arguments Pass On Launch". Then you can just pass argv[1] to your sqlite3_open().
精彩评论