📄 main.cpp
字号:
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <sqlite3.h>
#include <string.h>
#define BUF_LEN (1000)
#define SQL_ST "SELECT * FROM list WHERE name LIKE ?;"
/* assume the DB includes a table named 'list' consists of 'name' and etc. */
int main (int argc, char **argv)
{
sqlite3 *db;
int rc, len, i, cols, type;
char buf[BUF_LEN];
const char *next;
sqlite3_stmt *st;
if (argc != 2) {
fprintf(stderr, "Usage: %s DATABASE\n", argv[0]);
exit(EXIT_FAILURE);
}
rc = sqlite3_open(argv[1], &db);
if (rc != SQLITE_OK) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
exit(EXIT_FAILURE);
}
len = strlen(SQL_ST);
rc = sqlite3_prepare(db, SQL_ST, len, &st, &next);
if (rc != SQLITE_OK) {
fprintf(stderr, "Error on sqlite3_prepare: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
exit(EXIT_FAILURE);
}
printf("Please input name pattern.\n");
if (fgets(buf, BUF_LEN, stdin) == NULL) {
fprintf(stderr, "Something occurred on stdin\n");
exit(EXIT_FAILURE);
}
len = strlen(buf);
if (buf[len - 1] == '\n') {
len--;
buf[len] = '\0';
}
rc = sqlite3_bind_text(st, 1, buf, len, SQLITE_TRANSIENT);
if (rc != SQLITE_OK) {
fprintf(stderr, "Error on sqlite3_bind_text: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
exit(EXIT_FAILURE);
}
for (;;) {
rc = sqlite3_step(st);
if (rc == SQLITE_ROW) {
cols = sqlite3_column_count(st);
for (i = 0; i < cols; i++) {
type = sqlite3_column_type(st, i);
switch (type) {
case SQLITE_INTEGER:
printf("%s[%d] = %d\n", sqlite3_column_name(st, i),
i, sqlite3_column_int(st, i));
break;
case SQLITE_FLOAT:
printf("%s[%d] = %f\n", sqlite3_column_name(st, i),
i, sqlite3_column_double(st, i));
break;
case SQLITE_TEXT:
printf("%s[%d] = '%s'\n", sqlite3_column_name(st, i),
i, sqlite3_column_text(st, i));
break;
case SQLITE_BLOB:
printf("%s[%d] = BLOB[%d bytes]\n",
sqlite3_column_name(st, i),
i, sqlite3_column_bytes(st, i));
break;
case SQLITE_NULL:
printf("%s[%d] = NULL\n", sqlite3_column_name(st, i),
i);
break;
default:
printf("UNDEFINED Column[%d]\n", i);
break;
}
}
printf("\n");
} else if (rc == SQLITE_DONE) {
break;
} else {
fprintf(stderr, "Error on sqlite3_step: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
exit(EXIT_FAILURE);
}
}
rc = sqlite3_finalize(st);
if (rc != SQLITE_OK) {
fprintf(stderr, "Error on sqlite3_finalize: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
exit(EXIT_FAILURE);
}
sqlite3_close(db);
exit(EXIT_SUCCESS);
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -