sqlite数据库基本操作

资料地址  http://blog.chinaunix.net/uid-26833883-id-3239313.html
安装sqlite3
yum install -y sqlite-devel.x86_64




A.sqlite常用命令介绍
<1>是要打开的数据库文件。若该文件不存在,则自动创建
sqlite3 cwl.db
<2>显示所有命令
        sqlite> .help


<3>退出sqlite3
  sqlite>.quit


<4>显示当前打开的数据库文件
sqlite>.database


<5>显示数据库中所有表名
sqlite>.tables


<6>查看表的结构
sqlite>.schema


B.sqlite常用语句 


注意:每条语句都必须以";"结尾。


<1>创建新表
  sqlite>create  table    (f1  type1, f2  type2,…);
        例如:
         create table  people(id,name,age);


<2>删除表
sqlite>drop  table  
        例如:
        drop table people;


<3>向表中添加新记录
        sqlite>insert  into    values (value1, value2,…);
        例如:
        insert into people  values(1,'A',10);
        insert into people  values(2,'B',13);
        insert into people  values(3,'C',9);
        insert into people  values(4,'C',15);
        insert into people  values(5,NULL,NULL);
        注意: 字符串要用单引号括起来。


<4>查询表中所有记录
        sqlite>select  *  from  ;
        例如 :
        select   *   from  people;


<4>按指定条件查询表中记录
  sqlite>select  *  from    where  ;
        例如:
        在表中搜索名字是A的项所有信息
         select  *  from  people  where  name='A';
       
         在表中搜索年龄>=10并且<=15的项的所有信息
        select  *  from   people  where age>=10  and  age<=15;
        
        在表中搜索名字是C的项,显示其name和age
        select name,age from people where name='C';


        显示表中的前2项所有信息
        select  *  from  people  limit  2;
        
        显示以年龄排序表中的信息
        select * from people  order by age;
        
<6>按指定条件删除表中记录
    
sqlite>delete  from    where  
        
        例如:
        删除表中名字是'C'的项
        delete from pople  where name='C';


<7>更新表中记录


        sqlite>update    set  , …   where  ;  
        
        例如:
        将表中年龄是15并且ID是4项,名字改为CYG
        update  people set  name='cyg'  where  id=4 and  age=15;


<8>在表中添加字段
 
        sqlite>alter table add column ;
        
        例如:
        在people表中添加一个addr字段
        alter table  people add column addr;


C 解决删除字段问题
    今天在做数据库升级时,碰到要对原来数据库中一张表的一个字段名进行修改,但是用:
    alter table tablename rename column oldColumnName to newColumnName;


    始终不成功,后面查阅相关信息:
    SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.


    sqlite支持一个更改表内容的有限子集,就是说在sqlite更改表的命令中,只允许用户重命名表名或者增加多一个列到一个的表中。而重命名一个字段名和删除一个字段、或者增加和删除系统规定的参数这些操作是不可能的。


    解决办法:


    例如:在上面的操作过程中,我们在people表中新添加了一个字段addr,要删除这个字段,直接用sqlite的语句时无法完成的。
    我们可以这样干:
    A.将people表重命名为temp;
    B.重新创建people表;
    C.将temp表中的相应字段内容复制到people表中。
    D.删除temp表


    操作如下:
    A.alter table people rename to temp;
    B.create table people(id,name,age);
    C.insert  into  people  select  id,name,age  from temp;




<9>将id和age类型改为文本型
create table data_txt_table(id char(10),name char(10),age char(10),address varchar(15),hobby varchar (15));




四、导入data.txt文件到数据库(应先调用.seperator 设置‘,’ 为间隔符)
    sqlite> .separator "," 
    sqlite> .import data.txt data_txt_table
    sqlite> select * from data_txt_table;




五、 数据导出


   数据导出也是一个常用到的操作,可以将指定表中的数据导出成SQL脚本,供其他数据库使用,还可以将指定的数据表中的数据完整定位到标准输出,也可以将指定数据库中的数据完整的导入到另一个指定数据库等,


1. 导出成指定的SQL脚本
   将sqlite中指定的数据表以SQL创建脚本的形式导出,具体命令


    ywx@ywx:~/yu/sqlite$ sqlite3 test.db
    SQLite version 3.7.7.1 2011-06-28 17:39:05
    Enter ".help" for instructions
    Enter SQL statements terminated with a ";"
    sqlite> .output data.sql
    sqlite> .dump
    sqlite>


 


    ywx@ywx:~/yu/sqlite$ ll
    总计 16
    drwxr-xr-x 2 ywx ywx 4096 2011-08-13 23:15 ./
    drwxr-xr-x 7 ywx ywx 4096 2011-08-13 20:53 ../
    -rw-r--r-- 1 ywx ywx 602 2011-08-13 23:17 data.sql
    -rw-r--r-- 1 ywx ywx 2048 2011-08-13 22:44 test.db




2. 数据库导出


    data.sql test.db
    ywx@ywx:~/yu/sqlite$ sqlite3 test.db ".dump" | sqlite3 test2.db
    ywx@ywx:~/yu/sqlite$ ll
    总计 20
    drwxr-xr-x 2 ywx ywx 4096 2011-08-13 23:20 ./
    drwxr-xr-x 7 ywx ywx 4096 2011-08-13 20:53 ../
    -rw-r--r-- 1 ywx ywx 602 2011-08-13 23:17 data.sql
    -rw-r--r-- 1 ywx ywx 2048 2011-08-13 23:20 test2.db
    -rw-r--r-- 1 ywx ywx 2048 2011-08-13 22:44 test.db




3. 其他格式,如:htm格式输出


        ywx@ywx:~/yu/sqlite$ sqlite3 -html test.db "select * from data_txt_table" > liu.htm
        ywx@ywx:~/yu/sqlite$ ls
        data.sql liu.htm test2.db test.db










六、sqlite的一些常用API


<1>sqlite里最常用到的是sqlite3 *类型。从数据库打开开始,sqlite就要为这个类型准备好内存,直到数据库关闭,整个过程都需要用到这个类型。当数据库打开时开始,这个类型的变量就代表了你要操作的数据库,即句柄。


<2>int   sqlite3_open(char *path,sqlite3   **db);


功能:打开sqlite数据库


path:数据库文件路径(如果不存在,则创建)


db:指向sqlite句柄的指针


返回值:如果是SQLITE_OK则表示操作正常。相关的返回值sqlite定义了一些宏。具体这些宏的含义可以参考sqlite3.h文件。


<3>int   sqlite3_close(sqlite3  *db);


功能:关闭sqlite数据库


放回值:成功返回0,失败返回错误码


<4>const char *sqlite3_errmsg(sqlite3   *db);
返回值:返回错误信息


案例:


    #include <sqlite3.h>
    #include <errno.h>
    #include <stdlib.h>
    #include <stdio.h>


    int main(int argc,char *argv[])
    {
        sqlite3 **db;
        int result;


        if(argc < 2)
        {
            fprintf(stderr,"usage : %s argv[1].\n",argv[0]);
            exit(EXIT_FAILURE);
        }


        result = sqlite3_open(argv[1],&db);
        if(result != SQLITE_OK)
        {
            printf("Fail to sqlite3 open %s : %s.\n",argv[1],sqlite3_errmsg(db));
            exit(EXIT_FAILURE);
        }


        result = sqlite3_close(db);
        if(result != 0)
        {
            printf("Fail to sqlite3 close %s : %s.\n",argv[1],sqlite3_errmsg(db));
            exit(EXIT_FAILURE);
        }
        
        exit(EXIT_SUCCESS);
    }




<5>执行一条sql语句
typedef  int (*sqlite3_callback)(void *,int ,char **,char **);
int  sqlite3_exec
(
    sqlite3   *db ,  
    const  char *sql , 
    sqlite3_callback  callback   ,
    void  *arg,char  **errmsg 
);


a.第一个参数是前面sqlite3_open函数得到的指针。


b.第二个参数const  char   *sql是一条sql语句,以\0结尾。


c.第三个参数callbak是回调,当这条语句执行之后,sqlite3会去调用你提供的这个函数。


d.第四个参数void *是你提供的指针,你可以传递任何一个指针参数到这里,这个参数最终会传到回调函数里面,如果不需要传递指针给回调函数,可以填NULL。


e.第5个参数char  **errmsg是错误信息。注意是指针的指针。sqlite3里面有很多固定的错误信息。执行sqlite3_exec之后,执行失败是可以查阅这个指针;
例如:
char *errmsg;
调用sqlite3_exec,失败后printf("%s\n",errmsg)得到一串字符串信息,这串信息高诉你错在什么地方。sqlite3_exec函数通过修改你传入的指针的指针,把你提供的指针指向错误提示信息,这样sqlite3_exec函数外面就可以通过这个char *errmsg得到具体错误提示


说明:通常,sqlite3_callback和它后面的void *这两个位置都可以填NULL。填NULL表示你不需要回调。比如你做insert操作,做delete操作,就没有必要使用回调。而当你做select时,就要使用回调,因为sqlite3把数据查出来,得通过回调告诉你查出了什么数据。


返回值:成功返回0,失败返回错误码


exec的回调


typedef  int (*sqlite3_callback)(void  *para,int   n_column,char **column_value,char  **column_name);


a.通过para参数,你可以传入一些特殊的指针(比如类指针、结构指针),然后在这里面强制转换成对应的类型(这里面是void  *类型,必须强制转换成你的类型才可用)。然后操作这些数据。


b.n_column是这一条记录有多少个字段(即这条记录有多少列)。


c.char  **column_value是个关键值,查出来的数据都保存在这里,它实际上可以看做是一个一维的指针数组,每个元素都是一个char *值,是一个字段的内容(用字符串来表示,以\0结尾)。


d.char  **column_nam 跟column_value是对应的,表示这个字段的字段名称 。


//sqlite3的回调函数,sqlite每查到一条记录,就调用一次这个回调


int LoadMyInfo(void  *para,int  n_column,char  **column_value,char  ** column_name)
{
    //para是你在sqlite3_exec里传入的void  * 参数
    int     i;
    
    printf("记录包含%d个字段\n",n_column);
    for(i = 0;i < n_column;i ++)
    {
        printf("字段名 : %s  <->  字段值 : %s.\n",column_name[i],column_value[i]);
    }


    printf("--------------------------\n");
    
    return 0;
}


案例分析:


    #include <sqlite3.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>


    #define MAX 100


    typedef int (*sqlite3_callbak)(void *,int ,char **,char **);


    int ShowMyInfo(void *arg,int n_column,char **column_value,char **column_name)
    {
        int i = 0;


        for(i = 0;i < n_column;i ++)
        {
            printf("%s\t",column_name[i]);
        }


        printf("\n*************************************\n");


        for(i = 0;i < n_column;i ++)
        {
            printf("%s\t",column_value[i]);
        }


        printf("\n\n");


        return 0;
    }


    int exec_sql_string(char *sql_string,sqlite3 *db)
    {
        char *errmsg;


        if(sqlite3_exec(db,sql_string,ShowMyInfo,NULL,&errmsg) != 0)
        {
            fprintf(stderr,"Fail to exec sql(%s) : %s.\n",sql_string,errmsg);
            return -1;
        }


        return 0;
    }


    int main(int argc,char *argv[])
    {
        sqlite3 *db;
        int result;
        char sql_buf[MAX];


        if(argc < 2)
        {
            fprintf(stderr,"usage : %s argv[1].\n",argv[0]);
            exit(EXIT_FAILURE);
        }


        result = sqlite3_open(argv[1],&db);
        if(result != SQLITE_OK)
        {
            fprintf(stderr,"Fail to sqlite3_open %s : %s.\n",argv[1],sqlite3_errmsg(db));
            exit(EXIT_FAILURE);
        }


        while(1)
        {
            printf("sqlite >");
            fgets(sql_buf,sizeof(sql_buf),stdin);
            sql_buf[strlen(sql_buf) - 1] = '\0';
                    
                    if(strncmp(sql_buf,"quit",4) == 0)
                            break;


            exec_sql_string(sql_buf,db);
        }


        result = sqlite3_close(db);
        if(result != 0)
        {
            fprintf(stderr,"Fail to sqlite3_open %s : %s.\n",argv[1],sqlite3_errmsg(db));
            exit(EXIT_FAILURE);
        }


        exit(EXIT_SUCCESS);
    }








<6>不使用回调函数执行SQL语句


int   sqlite3_get_table
(
    sqlite3   *db,
    const char  *sql,
    char  ***resultp,
    int  *nrow,
    int  *ncolumn,
    char   **errmsg
);


功能:执行sql操作
db  :   数据库句柄
sql  :  sql语句
resultp  : 用来指向sql执行结果的指针
nrow  :  满足条件的记录的数目


ncolumn  :  每条记录包含的字段数目
注意:
从第0索引到第ncolumn-1索引都是字段的名称
从第ncolumn索引开始,后面都是字段的值


errmsg  :  错误信息指针的地址
返回值:成功返回0,失败返回错误码


实例:


    #include <sqlite3.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>


    #define MAX 100


    int exec_sql_string(char *sql_string,sqlite3 *db)
    {
        char *errmsg,**dbResult;
        int nRow,nColumn;
        int result,i,j,index;


        result = sqlite3_get_table(db,sql_string,&dbResult,&nRow,&nColumn,&errmsg);
        if(0 != result){
            fprintf(stderr,"Fail to exec sql(%s) : %s.\n",sql_string,errmsg);
            return -1;
        }
        
        //字段名字
        for(j = 0;j < nColumn;j ++)
        {
            printf("%s\t",dbResult[j]);
        }


        printf("\n");


        index = nColumn;//从它开始是字段对应的值


        for(i = 0;i < nRow;i ++)//查询到总共记录个数
        {
            for(j = 0;j < nColumn;j ++)
            {
                printf("%s\t",dbResult[index]);
                index ++;
            }
            printf("\n");
        }
        
        //释放查询结果所分配的内存
        sqlite3_free_table(dbResult);


        return 0;
    }


    int main(int argc,char *argv[])
    {
        sqlite3 *db;
        int result;
        char sql_buf[MAX];


        if(argc < 2)
        {
            fprintf(stderr,"usage : %s argv[1].\n",argv[0]);
            exit(EXIT_FAILURE);
        }


        result = sqlite3_open(argv[1],&db);
        if(result != SQLITE_OK)
        {
            fprintf(stderr,"Fail to sqlite3_open %s : %s.\n",argv[1],sqlite3_errmsg(db));
            exit(EXIT_FAILURE);
        }


        while(1)
        {
            printf("sqlite >");
            fgets(sql_buf,sizeof(sql_buf),stdin);
            sql_buf[strlen(sql_buf) - 1] = '\0';


            if(strncmp(sql_buf,"quit",4) == 0)
                break;


            exec_sql_string(sql_buf,db);
        }


        result = sqlite3_close(db);
        if(result != 0)
        {
            fprintf(stderr,"Fail to sqlite3_open %s : %s.\n",argv[1],sqlite3_errmsg(db));
            exit(EXIT_FAILURE);
        }


        exit(EXIT_SUCCESS);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值