前幾天隨便做的一個範例,以提供某天用到的時候作參考。
環境Cygwin+sqlite3
#ifdef SQLITE_ENABLE_ICU
#udefine SQLITE_ENABLE_ICU
#endif
/**//*
#ifndef SQLITE_CORE
#define SQLITE_CORE
#endif
*/
#include <stdio.h>
#include "sqlite3.h"
#include <iOStream>
using namespace std;
const char* sqlCreate ="CREATE TABLE items(id integer primary key, stocknum float, name varchar(30), price float, status varchar(12) )";
const char* sqlSelect ="SELECT stocknum,name,price FROM items ORDER BY stocknum";
const char* sqlInsert0="INSERT INTO items VALUES(NULL, 323.123, ''Product01'', 565.456, ''IN'')";
const char* sqlInsert1="INSERT INTO items VALUES(NULL, 423.123, ''莉?'', 665.456, ''IN'')";
const char* sqlInsert2="INSERT INTO items VALUES(NULL, 523.123, ''Product02'', 765.456, ''IN'')";
int printedHeader=0;
static int callback(void *NotUsed, int columns, char **azData, char **azColName)...{
int i;
if( printedHeader==0 )...{
printedHeader=1;
for(i=0; i<columns; i++)...{
printf("%s ", azColName[i]);
}
printf(" ");
}
for(i=0; i<columns; i++)...{
printf("%s ", azData[i] ? azData[i] : "NULL");
}
printf(" ");
return 0;
}
int main(int argc, char **argv)...{
cout<<"Begin, please waiting..."<<endl;
cout<<"Parameters:"<<endl;
for(int k=1; k<argc; k++)
cout<<" "<<k<<" -> "<<argv[k]<<endl;
cout<<endl;
sqlite3 *db;
char *zErrMsg = 0;
int rc;
if( argc!=3 )...{
printf("Usage: %s DATABASE SQL-STATEMENT ", argv[0]);
return(1);
}
rc = sqlite3_open(argv[1], &db);
if( rc )...{
printf("Can''t open database: %s ", sqlite3_errmsg(db));
sqlite3_close(db);
return(1);
}
rc = sqlite3_exec(db, sqlCreate, NULL, 0, &zErrMsg);
if( rc!=SQLITE_OK )...{
printf("Create SQL error: %s ", zErrMsg);
sqlite3_free(zErrMsg);
}
rc = sqlite3_exec(db, sqlInsert0, NULL, 0, &zErrMsg);
if( rc!=SQLITE_OK )...{
printf("INSERT SQL 0 error: %s ", zErrMsg);
sqlite3_free(zErrMsg);
}
rc = sqlite3_exec(db, sqlInsert1, NULL, 0, &zErrMsg);
if( rc!=SQLITE_OK )...{
printf("INSERT SQL 1 error: %s ", zErrMsg);
sqlite3_free(zErrMsg);
}
rc = sqlite3_exec(db, sqlInsert2, NULL, 0, &zErrMsg);
if( rc!=SQLITE_OK )...{
printf("INSERT SQL 2 error: %s ", zErrMsg);
sqlite3_free(zErrMsg);
}
rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg);
if( rc!=SQLITE_OK )...{
printf("SQL error: %s ", zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
printf("Finished, exit now. ");
return 0;
}