sql/sqlite/sqlite3 创建和打开数据库

时间:2022-09-14 17:45:25
<pre name="code" class="cpp">#include <iostream>
#include <string>
#include <tchar.h>
#include "sqlite3\\sqlite3.h"
#pragma comment (lib, "sqlite3\\sqlite3.lib")

static const char* data = "Callback function called";
static int callback(void *data, int argc, char **argv, char **pszColName){
	printf("%s: \n", (const char*)data);
	for(int i=0; i<argc; i++){
		printf("%s = %s\n", pszColName[i], argv[i] ? argv[i] : "NULL");
	}
	printf("\n");
	return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
	sqlite3 *pDataBase = NULL;
	char *pErrMsg = 0;
	int   iResult;
	char *pszSql = NULL;

	/* Open database */
	iResult = sqlite3_open("test.db", &pDataBase);
	if( iResult != SQLITE_OK)
	{
		printf( "Can't open database: %s\n", sqlite3_errmsg(pDataBase));
		exit(0);
	}else{
		printf( "Opened database successfully\n");
	}

	/* Create SQL statement */
	pszSql = "CREATE TABLE COMPANY("  \
		"ID INT PRIMARY KEY     NOT NULL," \
		"NAME           TEXT    NOT NULL," \
		"AGE            INT     ," \
		"ADDRESS        CHAR(50)," \
		"SALARY         REAL );";

	/* Execute SQL statement */
	iResult = sqlite3_exec(pDataBase, pszSql, callback, 0, &pErrMsg);
	if( iResult != SQLITE_OK ){
		printf( "SQL error: %s\n", pErrMsg);
		sqlite3_free(pErrMsg);
	}else{
		printf( "Table created successfully\n");
	}
	sqlite3_close(pDataBase);

	return 0;
}