【Linux】数据库编程

目录

 

基本SQL语句

创建表

删除表

插入记录

修改记录

删除记录

使用别名进行多表联合查询

sqlite3命令行工具

启动

执行操作

sqlite3编程接口 

头文件

关键数据结构

打开数据库

关闭数据库

执行sql语句

回调

不使用回调查询数据库的方法

例子


基本SQL语句

创建表

create table student(
    ID          INTEGER,
    name        TEXT,
    sex         TEXT,
    age         INTEGER,
    primary  key(ID)
);    

 SQLite中的数据类型 

  • NULL -- The value is a NULL value.
  • INTEGER -- The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
  • REAL -- The value is a floating point value, stored as an 8-byte IEEE floating point number.
  • TEXT -- The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE).
  • BLOB -- The value is a blob of data, stored exactly as it was input. 值是一个 blob 数据,完全根据它的输入存储。

注:SQLite 没有一个单独的用于存储日期和/或时间的存储类,但 SQLite 能够把日期和时间存储为 TEXT、REAL 或 INTEGER 值。

 

 可以以任何上述格式来存储日期和时间,并且可以使用内置的日期和时间函数来自由转换不同格式。

删除表

drop table student;

插入记录

insert into student values(1, 'Zhang', 'M', 18);

修改记录

update student set Sex = 'F', Age = 20 where Name = 'Zhang';

删除记录

delete from student where ID = 2;

使用别名进行多表联合查询

select A.name from student A, score B where A.id = B.id and B.score < 60;

 

sqlite3命令行工具

启动

在linux下启动sqlite3工具:

其中test.db是要操作的数据库文件,如果它不存在,则会自动创建一个新的空数据库。

执行操作

  • .exit ,退出sqlite互动模式的命令

  • .help,列出命令的提示信息。

  • .tables显示数据库中所有表名

  • .schema  <table_name查看表的结构

  • .database 显示当前打开的数据库文件

 

sqlite3编程接口 

具体的数据库函数的定义可以参考sqlite3.h文件。

gcc编译时要加上 -lsqlite3

头文件

#include <sqlite3.h>

关键数据结构

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

首先要定义一个sqlite3的对象,如:sqlite3 *database_;

打开数据库

int sqlite3_open( const char *filename, sqlite3 **ppDb );

参数

  • filename:数据库文件名,如:database.db。文件名不需要一定存在,如果此文件不存在,sqlite 会自动建立它。如果它存在,就尝试把它当数据库文件来打开。
  • ppDb:即关键数据结构
     

返回值

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

关闭数据库

int sqlite3_close(sqlite3 *);

执行sql语句

int sqlite3_exec(sqlite3*, const char *sql, sqlite3_callback, void *,  char **errmsg );
  • 即关键数据结构
  • sql:一条 sql 语句,以/0结尾。
  • sqlite3_callback :回调,当这条语句执行之后,sqlite3会去调用你提供的这个函数。
  • void * :你所提供的指针,你可以传递任何一个指针参数到这里,这个参数最终会传到回调函数里面,如果不需要传递指针给回调函数,可以填NULL。
  • char ** errmsg :错误信息。注意是指针的指针。sqlite3里面有很多固定的错误信息。执行 sqlite3_exec 之后,执行失败时可以查阅这个指针(直接 printf(“%s/n”,errmsg))得到一串字符串信息,这串信息告诉你错在什么地方。sqlite3_exec函数通过修改你传入的指针的指针,把你提供的指针指向错误提示信息,这样sqlite3_exec函数外面就可以通过这个 char*得到具体错误提示。
     

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

 

回调

这个函数得自己申明(也就是自己写的意思)

typedef int (*sqlite3_callback)(
void*,    /* Data provided in the 4th argument of sqlite3_exec() */
int,      /* The number of columns in row */
char**,   /* An array of strings representing fields in the row */
char**    /* An array of strings representing column names */
);

static int callback(void *data, int argc, char **argv, char **azColName){
   int i;
   for(i=0; i<argc; i++){
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("\n");
   return 0;
}

什么是回调函数?(大概就是函数指针的意思) 

/*一个简单的例子*/

#include <stdio.h>

int test(int i,int (*call)(int))
{
    printf("i = %d\n",i);

	call(i);
	return 0;
}

int test2(int i)
{
    printf("test2 %d",i);
	return 0;
}


int main()
{
    int (*a)(int,int (*)(int));
	a=test;
	a(10,test2);

    return 0;
}

不使用回调查询数据库的方法

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

参数

  • resultp:查询结果,一一维数组,第一行是字段名称,后面是紧接着的每个字段的值
  • nrow:查询出多少条记录(即查出多少行)
  • ncolumn:多少个字段(多少列)。

例子

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

static int callback(void *data,int argc,char **argv,char **columnname)
{
    int i;
    printf("%s",(char*)data);

    for(i = 0; i < argc; i++)
    {
        printf("%s-----%s  ",columnname[i],argv[i]);
    }
    printf("\n");

    return 0;
}

int main()
{
    sqlite3 *db;
    int ret;
    char *sql;
    char *errmsg;
    char *record = "record is:\n";
    int i, j ,index;
    char **result;
    int row, column;


    ret = sqlite3_open("test.db",&db);
    if(ret != SQLITE_OK)
    {
        printf("sqlite3_open error,%s\n",sqlite3_errmsg(db));
        return -1;
    }

#if 0
    sql = "create table student(\
           id int primary key not null,\
           name text nuot null);";
    ret = sqlite3_exec(db,sql,NULL,NULL,&errmsg);
    if(ret != SQLITE_OK)
    {
        printf("sqliete3_exec error,%s\n",errmsg);
        return -1;
    }
    printf("create success!\n");
#endif

#if 0
    sql = "insert into student values(3,'Yvette');";
    ret = sqlite3_exec(db,sql,NULL,NULL,&errmsg);
    if(ret != SQLITE_OK)
    {
        printf("sqliete3_exec error,%s\n",errmsg);
        return -1;
    }
    printf("insert success!\n");
#endif

    sql = "select * from student;";
    ret = sqlite3_exec(db,sql,callback,(void *)record,&errmsg);
    if(ret != SQLITE_OK)
    {
        printf("select error,%s\n",errmsg);
        return -1;
    }
    printf("select success!\n");

    ret = sqlite3_get_table(db,sql,&result,&row,&column,&errmsg);
    if(ret != SQLITE_OK)
    {
        printf("select error,%s\n",errmsg);
        return -1;
    }
    printf("select success!\n");

    printf("%s     %s\n",result[0],result[1]);
    index = column;

    for(i = 0; i < row; i++)
    {
        for(j = 0; j < column; j++)
        {
            printf("%s     ",result[index++]);
        }
        printf("\n");
    }

    sqlite3_close(db);
    return 0;
}

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值