嵌入式Linux使用Sqlite3

1.CMakeList.txt

CMakeList.txt中需要指明库文件路径,头文件路径,交叉编译工具链。

cmake_minimum_required(VERSION 3.5.1)

project(BANANAPEELX)
##设置交叉编译工具链
set(TOOLCHAIN_DIR /usr/local/arm/gcc-linaro-4.9.4-2017.01-x86_64_arm-linux-gnueabihf/bin)
set(CMAKE_CXX_COMPILER ${TOOLCHAIN_DIR}/arm-linux-gnueabihf-g++)
set(CMAKE_C_COMPILER ${TOOLCHAIN_DIR}/arm-linux-gnueabihf-gcc)

set(DATABASE_LIBS sqlite3)
##添加头文件路径
include_directories(.) 
include_directories(/home/alientek/sqlite-autoconf-3420000/install/include) 
##添加库目录
link_directories(/home/alientek/sqlite-autoconf-3420000/install/lib)

##add_executable(hello test_database.c)
set(SRC_LIST test_database.c)
add_executable(test_database ${SRC_LIST})

##链接库
target_link_libraries(test_database ${DATABASE_LIBS}  )

2.源文件

test_database.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include "sqlite3.h"

char        DBFileName[80];
char        DBTableName[20];

int main(  int argc,char* argv[] )
{
	char 		SqlStr[256];
	char*        ErrMsg;
	char 		str[64];
	int			startidx;
	int         i1, rc;
	time_t      t;
	struct tm   *p;
	sqlite3*     db;
	
	startidx = 0;
	strcpy( DBFileName, "/home/mydatabase/test.db");
	strcpy( DBTableName, "table1");

	//创建数据库文件
	rc = sqlite3_open( DBFileName, &db );

	sprintf( SqlStr, "create table %s(Name char(50), Value int, Date char(50))",
			         DBTableName );
	//创建表
	sqlite3_exec( db, SqlStr, 0, 0, &ErrMsg );

	//往表里插入10条记录
	for( i1=startidx; i1<startidx+10; i1++ )
	{
		time( &t );
		p = localtime ( &t );
		sprintf( str, "%d.%d.%d-%d:%d:%d\n", p->tm_year + 1900, p->tm_mon+1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec );
		printf("%d\n", i1+1);
		sprintf(SqlStr, "insert into %s values(\"Name%d\", %d, \"%s\")",
				         DBTableName, i1+1, i1+1, str );
		sqlite3_exec( db, SqlStr, 0, 0, &ErrMsg );//执行sql语句sqlite3_exec
		sleep(1);
	}

	sqlite3_close( db );

	return 0;
}

3.创建并写入

编译后将可执行文件拷贝到开发板
创建数据库test.db

sqlite3 test.db

后执行

./test_database

在这里插入图片描述

4.查看数据库

sqlite3 test.db
.schema
select * from table1;

在这里插入图片描述
数据库更多操作参考:
数据库命令

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_45281309

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值