#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);
}
|