doc: update the SQLite C interoperability example

pull/5798/head
Delyan Angelov 2020-07-11 10:49:42 +03:00
parent 006d260d20
commit d44fe50953
1 changed files with 32 additions and 9 deletions

View File

@ -1713,15 +1713,29 @@ fn main(){
#flag -lsqlite3
#include "sqlite3.h"
struct C.sqlite3
struct C.sqlite3_stmt
// See also the example from https://www.sqlite.org/quickstart.html
struct C.sqlite3{}
struct C.sqlite3_stmt{}
fn C.sqlite3_open(charptr, C.sqlite3)
fn C.sqlite3_column_int(stmt C.sqlite3_stmt, n int) int
// Or just define the type of parameter & leave C. prefix
fn C.sqlite3_prepare_v2(sqlite3, charptr, int, sqlite3_stmt, charptr) int
fn C.sqlite3_step(sqlite3)
fn C.sqlite3_finalize(sqlite3_stmt)
type FnSqlite3Callback fn(voidptr, int, &charptr, &charptr) int
fn C.sqlite3_open(charptr, &&C.sqlite3) int
fn C.sqlite3_close(&C.sqlite3) int
fn C.sqlite3_column_int(stmt &C.sqlite3_stmt, n int) int
// ... you can also just define the type of parameter & leave out the C. prefix
fn C.sqlite3_prepare_v2(&sqlite3, charptr, int, &&sqlite3_stmt, &charptr) int
fn C.sqlite3_step(&sqlite3_stmt)
fn C.sqlite3_finalize(&sqlite3_stmt)
fn C.sqlite3_exec(db &sqlite3, sql charptr, FnSqlite3Callback, cb_arg voidptr, emsg &charptr) int
fn C.sqlite3_free(voidptr)
fn my_callback(arg voidptr, howmany int, cvalues &charptr, cnames &charptr) int {
for i in 0..howmany {
print('| ${cstring_to_vstring(cnames[i])}: ${cstring_to_vstring(cvalues[i]):20} ')
}
println('|')
return 0
}
fn main() {
path := 'users.db'
@ -1733,7 +1747,16 @@ fn main() {
C.sqlite3_step(stmt)
nr_users := C.sqlite3_column_int(stmt, 0)
C.sqlite3_finalize(stmt)
println(nr_users)
println('There are $nr_users users in the database.')
//
error_msg := charptr(0)
query_all_users := 'select * from users'
rc := C.sqlite3_exec(db, query_all_users.str, my_callback, 7, &error_msg)
if rc != C.SQLITE_OK {
eprintln( cstring_to_vstring(error_msg) )
C.sqlite3_free(error_msg)
}
C.sqlite3_close(db)
}
```