一、Linux环境sqlite3安装
安装sqlite数据库
sudo apt install sqlite3
安装后,可以通过sqlite3 --version查看是否安装成功。
如果打印出了版本号,这样你就可以在终端使用sqlite3的服务了。
使用 .show 命令,来查看 SQLite 命令提示符的默认设置。
如果输入命令,不管怎么回车都不能退出,就算输入 .quit 都不能退出,只能被迫 Ctrl + C *2退出sqlite,重新进入,不要着急;输入 ; 回车解决。
二、Linux环境的sqlite3源码方式安装
先安装wget服务,通过wget获取sqlite3的源码
sudo apt install wget
安装好wget服务之后,在本地创建一个目录
cd ~
mkdir sqlite-source
cd sqllite-source
wget https://www.sqlite.org/2016/sqlite-autoconf-3110000.tar.gz
此时需要解压sqlite-autoconf-3110000.tar.gz文件,本地没有tar工具的安装一下,有则跳过这一步。
sudo apt install tar
解压
tar -zxvf sqlite-autoconf-3110000.tar.gz //你会在你命令行的同级目录得到一个sqlite-autoconf-3110000文件,可通过ls查看
指定安装路径
在你的加目录下创建一个平时放第三方库的文件夹。
mkdir -p ~/3party/sqlite3
指定sqlite库文件、头文件和可行性命令的安装路径
cd ~/sqlite-autoconf-3110000
./configure --prefix=~/3party/sqlite3
编译
进入到你的sqlite-autoconf-3110000目录,编译。
make clean; make
安装
make install
现在你的3dparty/sqlite3下面就有如下文件了,
使用测试
创建main.cpp
#include <iostream>
#include <stdio.h>
#include <sqlite3.h>
using namespace std;
int callback(void* ,int nCount,char** pValue,char** pName) {
string str;
for(int i=0;i<nCount;i++) {
str += pName[i];
str += ":";
s += pValue[i];
s += "\n";
}
// show the table's information
cout<<s<<endl;
return 0;
}
int main()
{
sqlite3 *handle = NULL;
int nResult = 0;
char* errmsg;
// Open the file to get a database handle
nResult = sqlite3_open("test.db", &handle);
if (nResult != SQLITE_OK) {
printf("数据库打开失败, 原因 : %s\n", sqlite3_errmsg(handle));
return 0;
}
// create data table
nResult = sqlite3_exec(handle, "create table person(id integer primary key autoincrement,name varchar(5))", NULL, NULL, &errmsg);
if (nResult != SQLITE_OK) {
sqlite3_close(handle);
cout << errmsg << endl;
sqlite3_free(errmsg);
return 0;
}
string strSql; //sql command
strSql += "begin;\n";
for (int i = 0; i < 3; i++) {
strSql += "insert into person values(null,'zhou');\n";
}
strSql += "commit;";
// cout<<strSql<<endl;
// insert data to the person table
nResult = sqlite3_exec(handle, strSql.c_str(), NULL, NULL, &errmsg);
if (nResult != SQLITE_OK) {
sqlite3_close(handle);
cout << errmsg << endl;
sqlite3_free(errmsg);
return 0;
}
strSql = "select * from person";
nResult = sqlite3_exec(handle, strSql.c_str(), callback, NULL, &errmsg);
if (nResult != SQLITE_OK) {
sqlite3_close(handle);
cout << errmsg << endl;
sqlite3_free(errmsg);
return 0;
}
sqlite3_close(handle);
return 0;
}
编译时,指定你编译生成的sqlite3路径
gcc main.cpp -I/home/< username >/3party/sqlite3/include -L/home/< username >/3party/sqlite3/lib -lsqlite3
运行
./a.out
运行结果