因爲網上關於純C接口的文章並很少,本人在工做中恰好接觸到,在這裏作一點小分享。
廢話不說,先上下載地址 http://packages.couchbase.com...。html
如下是官方代碼:數據庫
#include <libcouchbase/couchbase.h> #include <stdlib.h> #include <stdio.h> #include <string.h> static void error_callback(lcb_t instance, lcb_error_t err, const char *errinfo) { fprintf(stderr, "Error %s: %s", lcb_strerror(instance, err), errinfo ? errinfo : ""); exit(EXIT_FAILURE); } /* the callback invoked by the library when receiving a get response */ static void get_callback(lcb_t instance, const void *cookie, lcb_error_t error, const lcb_get_resp_t *resp) { if (error != LCB_SUCCESS) { fprintf(stderr, "Failed to retrieve \""); fwrite(resp->v.v0.key, 1, resp->v.v0.nkey, stderr); fprintf(stderr, "\": %s\n", lcb_strerror(instance, error)); } else { fprintf(stderr, "Data for key: \""); fwrite(resp->v.v0.key, 1, resp->v.v0.nkey, stderr); fprintf(stderr, "\" is : "); fwrite(resp->v.v0.bytes, 1, resp->v.v0.nbytes, stderr); } (void)cookie; /* ignore */ } int main(void) { struct lcb_create_st create_options; lcb_t instance; lcb_error_t err; memset(&create_options, 0, sizeof(create_options)); create_options.v.v0.host = "myserver:8091"; create_options.v.v0.user = "mybucket"; create_options.v.v0.passwd = "secret"; create_options.v.v0.bucket = "mybucket"; err = lcb_create(&instance, &create_options); if (err != LCB_SUCCESS) { fprintf(stderr, "Failed to create libcouchbase instance: %s\n", lcb_strerror(NULL, err)); return 1; } /* set up the handler to catch all errors */ lcb_set_error_callback(instance, error_callback); /* initiate the connect sequence in libcouchbase */ err = lcb_connect(instance); if (err != LCB_SUCCESS) { fprintf(stderr, "Failed to initiate connect: %s\n", lcb_strerror(NULL, err)); return 1; } /* run the event loop and wait until we've connected */ lcb_wait(instance); /* set up a callback for our get requests */ lcb_set_get_callback(instance, get_callback); { lcb_get_cmd_t cmd; const lcb_get_cmd_t *commands[1]; commands[0] = &cmd; memset(&cmd, 0, sizeof(cmd)); cmd.v.v0.key = "foo"; cmd.v.v0.nkey = 3; err = lcb_get(instance, NULL, 1, commands); if (err != LCB_SUCCESS) { fprintf(stderr, "Failed to get: %s\n", lcb_strerror(NULL, err)); return 1; } } lcb_wait(instance); lcb_destroy(instance); exit(EXIT_SUCCESS); }
create_options.v.v0.host = "myserver:8091";cookie
**請注意如下兩句話,若是按照官方的標準調用的話,有可能提示管理員帳號沒法訪問數據庫錯誤,註釋後成功訪問!!!** //create_options.v.v0.user = "mybucket"; //create_options.v.v0.passwd = "secret"; create_options.v.v0.bucket = "mybucket";