#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "db.h"
typedef struct
{
int id;
int age;
char nm[32];
char addr[128];
} per;
typedef struct
{
db *db;
char *dbnm;
} per_db;
static per_db per_db[] = {null, "per.db"};
static int per_db_init(per_db *per)
{
int ret;
db *db;
if ((ret = db_create(&db, null, 0)) != 0)
{
fprintf(stderr, "db_create error:%s\n", db_strerror(ret));
return (-1);
}
per->db = db;
ret = db->open(db, null, per->dbnm, null, db_btree, db_create, 0);
if (ret != 0)
{
fprintf(stderr, "db->open error:%s\n", db_strerror(ret));
return (-1);
}
return (0);
}
static void per_db_term(per_db *per)
{
db *db = per->db;
if (db)
db->close(db, 0);
}
static void get_data(per *p)
{
p->id = random();
snprintf(p->nm, 32, "nm%x", p->id);
p->age = random()/2;
snprintf(p->addr, 128, "addr%x", p->age);
}
static int per_db_putdata(db *db)
{
int i, ret;
dbt key, v;
per per;
for (i = 0; i < 10; i)
{
memset(&key, 0x00, sizeof(dbt));
memset(&v, 0x00, sizeof(dbt));
get_data(&per);
per.id = i;
printf("[%d]:: id.%d age.%d nm.%s addr.%s\n"
, i, per.id, per.age, per.nm, per.addr);
key.data = &per.id;
key.size = sizeof(int);
v.data = &per;
v.size = sizeof(per);
ret = db->put(db, 0, &key, &v, db_nooverwrite);
if (ret != 0)
{
fprintf(stderr, "db->put error:%s\n", db_strerror(ret));
return (-1);
}
}
return (0);
}
static int per_db_getdata(db *db)
{
int ret, i;
dbc *dbc;
dbt key, v;
per *per;
i = 0;
memset(&key, 0x00, sizeof(dbt));
memset(&v, 0x00, sizeof(dbt));
ret = db->cursor(db, null, &dbc, 0);
if (ret != 0)
{
fprintf(stderr, "db->cursor error:%s\n", db_strerror(ret));
return (-1);
}
printf("get data: \n");
while ((ret = dbc->c_get(dbc, &key, &v, db_next)) == 0)
{
per = (per *)v.data;
printf("[%d] id.%d age.%d nm.%s addr.%s \n"
, i, per->id, per->age, per->nm, per->addr);
}
dbc->c_close(dbc);
return (0);
}
/*
* main function()
*/
int main(int argc, char **argv)
{
per_db *per = per_db;
srandom(time(null));
/* create database */
if (per_db_init(per) < 0)
goto err_1;
/* insert data */
if (per_db_putdata(per->db) < 0)
{
per_db_term(per);
goto err_1;
}
/* search data and print */
if (per_db_getdata(per->db) < 0)
{
per_db_term(per);
goto err_1;
}
/* close database */
per_db_term(per);
return (0);
err_1:
return (-1);
}
|