[程式碼例項][C語言][sqlite3]用SQL語句查詢資料庫的例項
阿新 • • 發佈:2019-01-08
下載sqlite3原始碼
編譯安裝sqlite3的Makefile
INSTALL_PATH =/usr/local
all: install
libsqlite3.so: sqlite3.c sqlite3.h
gcc -shared -fPIC $< -o [email protected]
install_lib: libsqlite3.so install_headers
cp libsqlite3.so $(INSTALL_PATH)/lib
ldconfig $(INSTALL_PATH)/lib
install_headers: sqlite3.h sqlite3ext.h
cp $^ $(INSTALL_PATH)/include/
sqlite3: install_lib shell.c
$(CC) shell.c -o [email protected] -lsqlite3 -lpthread -ldl
install_shell: sqlite3
cp $^ $(INSTALL_PATH)/bin
install: install_lib install_shell
uninstall:
rm -f \
$(INSTALL_PATH)/lib/libsqlite3.so \
$(INSTALL_PATH)/include/sqlite3.h \
$(INSTALL_PATH)/include/sqlite3ext.h \
$(INSTALL_PATH)/bin/sqlite3
clean:
rm -f *.so sqlite3
.PHONY: install install_lib install_headers install_shell clean
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
客戶端程式
/*
* main.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void * not_used, int argc, char * argv[], char * col_names[]);
int main(int argc, char * argv[])
{
sqlite3 * db = NULL;
char * zErrMsg = NULL;
if(argc != 3)
{
fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]);
return EXIT_FAILURE;
}
if(sqlite3_open(argv[1], &db) != SQLITE_OK)
{
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return EXIT_FAILURE;
}
if(sqlite3_exec(db, argv[2], callback, NULL, &zErrMsg) != SQLITE_OK)
{
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
return EXIT_SUCCESS;
}
static int callback(void * not_used, int argc, char * argv[], char * col_names[])
{
for(int i; i < argc; i++)
printf("%s = %s\n", col_names[i], argv[i] ? argv[i] : "NULL");
printf("\n");
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
編譯客戶端程式的Makefile
all: main
main: main.c
gcc main.c -o main -lsqlite3 -lpthread -ldl
clean:
rm -r main
.PHONY: clean
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
資料庫指令碼檔案
/*
* test.sql
*/
DROP TABLE main.user;
CREATE TABLE main.user(
Name TEXT,
Age INTEGER
);
INSERT INTO user VALUES('Huo Yun', 27);
INSERT INTO user VALUES('Gao Jingzhuo', 30);