Use hisqry_open() to open a database, hisqry_exec() to execute SQL statements, and hisqry_close() to close an open database. These APIs returns 0 to indicate successful operation.
In case of an error, use hisqry_errmsg() to extract the last error message. The nullptr indicates no errors from the last operation.
Name | Functionality / Arguments / Return Value |
---|---|
int hisqry_open( const char* filename, hisqrydb** db ) |
Opens a database.
Even if open fails, a pointer is returned from "db" argument.
This is to extract error message.
As a result, a database ptr must be released with hisqry_close().
|
int hisqry_exec( hisqrydb* db, const char* sql, int ( *callback )( void* int, char**, char** ), void* data ) |
Executes SQL statements. Multiple SQL statements can be supplied.
The execution stops at the first error.
|
int hisqry_close( hisqrydb* db ) |
Closes a database.
hisqry_close() must be always called after hisqry_open() to release resources.
|
const char* hisqry_errmsg( hisqrydb* db ) |
Obtains the last error message from a database instance.
|
The below code is an example with explanations:
1 #include <stdio.h>
2 #include <hisqryc.h>
3
4 static int callback( void* data, int argc, char **argv, char **colName )
5 {
6 if( data )
7 printf( "%s\n", ( char* ) data );
8 int i;
9 for( i = 0; i < argc; i++ )
10 printf( "%s%s === %s",
11 i == 0 ? "" : " ",
12 colName[ i ], argv[ i ] ? argv[ i ] : "NULL" );
13 printf( "\n" );
14 return 0;
15 }
16
17 int main( int argc, char* argv[] )
18 {
19 hisqrydb *db;
20 int rc;
21
22 rc = hisqry_open( "hisqryc-example.sql", &db );
23 if( rc )
24 {
25 fprintf( stderr, "Can't open database: %s\n", hisqry_errmsg( db ) );
26 return 0;
27 }
28 printf("Opened database\n");
29
30 char *sql[] =
31 {
32 "VALUES ( 999 );",
33 "CREATE TABLE test1 ( number INT, str STRING );",
34 "INSERT INTO test1 VALUES ( 0, \"zero\" ), ( 1, \"one\" ), ( 2, \"two\" );",
35 "INSERT INTO test1 VALUES ( 10, \"ten\" );",
36 "INSERT INTO test1 VALUES ( -1, \"-1\" ); INSERT INTO test1 VALUES ( -2, \"-2\" );",
37 "SELECT * FROM test1;",
38 "UPDATE test1 SET number = 10 * number;",
39 "SELECT * FROM test1;",
40 "SELECT * FROM ;",
41 "INSERT INTO test1 VALUES ( -11, \"-11\" ); SELECT * FROM ; INSERT INTO test1 VALUES ( -12 );",
42 "SELECT * FROM test1 WHERE number < 0;",
43 "DROP TABLE test1;",
44 "CREATE TABLE test2 ( number1 INT, number2 INT );",
45 "INSERT INTO test2 VALUES ( 88, 99 );",
46 "SELECT * FROM test2;",
47 "DROP TABLE test2;",
48 };
49
50 for( int i = 0; i < sizeof( sql ) / sizeof( sql[ 0 ] ); i++ )
51 {
52 rc = hisqry_exec( db, sql[ i ], callback, sql[ i ] );
53 if( rc != 0 )
54 {
55 const char *err = hisqry_errmsg( db );
56 fprintf( stderr, "SQL input='%s' error=>%s\n", sql[ i ], err );
57 }
58 else
59 printf( "success\n" );
60 }
61
62 hisqry_close( db );
63 }