Simple example of creating a Database, inserting some items, search for these items and erase them
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#if UNDER_CE
# include <windows.h>
#endif
#include <ham/hamsterdb.h>
#define LOOP 10
void
error(const char *foo, ham_status_t st)
{
#if UNDER_CE
wchar_t title[1024];
wchar_t text[1024];
MultiByteToWideChar(CP_ACP, 0, foo, -1, title,
sizeof(title)/sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, ham_strerror(st), -1, text,
sizeof(text)/sizeof(wchar_t));
MessageBox(0, title, text, 0);
#endif
printf("%s() returned error %d: %s\n", foo, st, ham_strerror(st));
exit(-1);
}
int
main(int argc, char **argv)
{
int i;
ham_status_t st;
ham_db_t *db;
ham_key_t key;
ham_record_t record;
memset(&key, 0, sizeof(key));
memset(&record, 0, sizeof(record));
st=ham_new(&db);
if (st!=HAM_SUCCESS)
error("ham_new", st);
st=ham_create(db, "test.db", 0, 0664);
if (st!=HAM_SUCCESS)
error("ham_create", st);
for (i=0; i<LOOP; i++) {
key.data=&i;
key.size=sizeof(i);
record.size=key.size;
record.data=key.data;
st=ham_insert(db, 0, &key, &record, 0);
if (st!=HAM_SUCCESS)
error("ham_insert", st);
}
for (i=0; i<LOOP; i++) {
key.data=&i;
key.size=sizeof(i);
st=ham_find(db, 0, &key, &record, 0);
if (st!=HAM_SUCCESS)
error("ham_find", st);
if (*(int *)record.data!=i) {
printf("ham_find() ok, but returned bad value\n");
return (-1);
}
}
st=ham_close(db, 0);
if (st!=HAM_SUCCESS)
error("ham_close", st);
st=ham_open(db, "test.db", 0);
if (st!=HAM_SUCCESS)
error("ham_open", st);
for (i=0; i<LOOP; i++) {
key.size=sizeof(i);
key.data=&i;
st=ham_erase(db, 0, &key, 0);
if (st!=HAM_SUCCESS)
error("ham_erase", st);
}
for (i=0; i<LOOP; i++) {
key.size=sizeof(i);
key.data=&i;
st=ham_find(db, 0, &key, &record, 0);
if (st!=HAM_KEY_NOT_FOUND)
error("ham_find", st);
}
st=ham_close(db, 0);
if (st!=HAM_SUCCESS)
error("ham_close", st);
ham_delete(db);
#if UNDER_CE
error("success", 0);
#endif
printf("success!\n");
return (0);
}
#if UNDER_CE
int
_tmain(int argc, _TCHAR* argv[])
{
return (main(0, 0));
}
#endif