3 #include 4 #include "md5.h"
5
6 /*定义此宏时使用回调函数查询否则只是用非回调函数查询*/
7 //#define CALLBACK
8
9 /*定义创建表格指令IF not EXISTS:不存在,AUTOINCREMENT:自动增加主键,not NULL:不能为空*/
10 #define CREATE "create table IF not EXISTS passwd(id integer primary key AUTOINCREMENT,username text not NULL,password text not NULL)"
11 /*定义查询数据指令*/
12 #define SELECT "select * from passwd where username=‘%s‘ and password=‘%s‘"
13 /*定义插入数据指令*/
14 #define INSERT "insert into passwd(username,password) values(‘%s‘,‘%s‘)"
15
16 /*如果查询到多行数据, 那么这个函数就会调用多次(每一行调用一次)*/
17 int callback(void *arg, int col, char **value, char **name)
18 {
19 int i=0;
20 for(i=0;i
21 {
22 printf("%s\t", value[i]);
23 }
24 printf("\n");
25 return 0;
26 }
27
28
29 int main(void)
30 {
31
32 //1.打开数据库
33 sqlite3 *ppdb = NULL;
34 int ret = sqlite3_open("./passwd", &ppdb); /*我们之前要先创建一个名字叫passwd的数据库*/
35 if(ret != SQLITE_OK)
36 {
37 perror("open fail");
38 return -1;
39 }
40 sqlite3_exec(ppdb,CREATE,NULL,NULL,NULL); /*创建一个表格*/
41 char temp[32];
42 char temp1[32];
43 char insert[strlen(temp)+strlen(temp1)+200]; /*这里的数组要给大一点,因为等下加密的时候会得到一串很长的数据*/
44 printf("please input your username:");
45 scanf("%s",temp);
46 printf("please input your password:");
47 scanf("%s",temp1);
48 MD5Str(temp1,temp1);/*把输入的密码使用md5加密存储在数据库表格中*/
49 printf("1111\n");
50
51
52 sprintf(insert,INSERT,temp,temp1);/*打包数据,准备插入到表格中*/
53
54 sqlite3_exec(ppdb,insert,NULL,NULL,NULL);
55
56
57 char username[32];
58 char password[33];
59 printf("input username:");
60 scanf("%s",username);
61 printf("input password:");
62 scanf("%s",password);
63
64 MD5Str(password,password);/*把输入的密码使用md5加密之后与数据库表格中的密码匹对*/
65 char sql[strlen(SELECT)+strlen(username)+strlen(password)];
66
67 /*打包一个字符串,将SELECT字符串放到sql中,username和password这两个变量放大SELECT中*/
68 sprintf(sql,SELECT,username,password);
69
70
71 #ifdef CALLBACK
72 //回调查询
73 char *selectsql = "select * from myname";
74 ret = sqlite3_exec(ppdb, selectsql, callback, NULL, NULL);
75 if(ret != SQLITE_OK)
76 {
77 perror("create fail");
78 sqlite3_close(ppdb);
79 return -1;
80 }
81
82 //非回调查询
83 #else
84 char **result = NULL;
85 int row = 0;
86 int col = 0;
87 char *error = NULL;
88 ret = sqlite3_get_table(ppdb,sql,&result,&row,&col,&error);
89 if(ret != SQLITE_OK)
90 {
91 perror("get table fail");
92 return -1;
93 }
94
95 int i=0, j=0;
96 for(i=0;i
97 {
98 for(j=0;j
99 {
100 printf("%s\t",result[j+i*col]);
101 }
102 printf("\n");
103 }
104
105 if(row > 0) /*数据匹配成功*/
106 printf("checked OK\n");
107 else /*数据匹配失败*/
108 printf("fail\n");
109 sqlite3_free_table(result);//释放结果
110 #endif
111
112
113 sqlite3_close(ppdb);
114 return 0;
115 }
View Code
我们先要创建一个名字叫passwd数据库,如果不懂创建可以看看我的这篇文章:linux数据库环境搭建
sqlite3 passwd
接着我们编译程序
gcc -o mysqlite3 mysqlite3.c -lsqlite3 -lmd5