sqlite | c++ | demo

发布时间:2024年01月16日

sqlite 过得的废话 就不细说了
接下来,主要讲 安装sqlite 然后写一个demo ,然后再shell 命令操作sqlite

#安装 sqlite 程序 以及开发包	我的linux 环境是centos
sudo yum install sqlite-3.7.17-8.el7_7.1.x86_64 sqlite-devel

#输入 sqlite3 测试是否安装成功  libsqlite3.so 	/usr/lib64/libsqlite3.so
sqlite3
 
find / -name libsqlite3.so
#include <iostream>
#include <sqlite3.h>
using namespace std;

static int callback(void *NotUsed, int argc, char **argv, char **azColName)
{
	int i;
	for(i=0; i<argc; i++)
	{
		cout<<azColName[i]<<" = " << (argv[i] ? argv[i] : "NULL")<<"\n";
	}
	cout<<"\n";
	return 0;
}
  
int main()
{
	const int STATEMENTS = 8;
	sqlite3 *db;
	char *zErrMsg = 0;
	const char *pSQL[STATEMENTS];
	int rc;
  
	rc = sqlite3_open("familyGuy.db", &db);

	if( rc )
	{
		cout<<"Can't open database: "<<sqlite3_errmsg(db)<<"\n";
	} 
	else
	{
		cout<<"Open database successfully\n\n";
	}

	pSQL[0] = "create table myTable (FirstName varchar(30), LastName varchar(30), Age smallint, Hometown varchar(30), Job varchar(30))";

	pSQL[1] = "insert into myTable (FirstName, LastName, Age, Hometown, Job) values ('Peter', 'Griffin', 41, 'Quahog', 'Brewery')";
	
	pSQL[2] = "insert into myTable (FirstName, LastName, Age, Hometown, Job) values ('Lois', 'Griffin', 40, 'Newport', 'Piano Teacher')";
	
	pSQL[3] = "insert into myTable (FirstName, LastName, Age, Hometown, Job) values ('Joseph', 'Swanson', 39, 'Quahog', 'Police Officer')";
	
	pSQL[4] = "insert into myTable (FirstName, LastName, Age, Hometown, Job) values ('Glenn', 'Quagmire', 41, 'Quahog', 'Pilot')";

	pSQL[5] = "select * from myTable";
	
	pSQL[6] = "delete from myTable"; 

	pSQL[7] = "drop table myTable";

	for(int i = 0; i < STATEMENTS; i++)
	{
		rc = sqlite3_exec(db, pSQL[i], callback, 0, &zErrMsg);
		if( rc!=SQLITE_OK )
		{
			cout<<"SQL error: "<<sqlite3_errmsg(db)<<"\n";
			sqlite3_free(zErrMsg);
			break;
		}
	}

	sqlite3_close(db);

	return 0;
}
g++  test.cpp -o test  -std=c++11 -lsqlite3

./test

#####注意这是一个创(机制是先找再创) 库familyGuy.db 建表myTable
#####插入四条记录,然后打印所有该表所有内容最后删表

demoe 的链接在下方
c++demo

#########################
然后在shell 中查看数据库

###首先要进入 你创建demo 的路径 因为数据库是在该目录常见的 但要###注意  /root 路径下也会有该数据库
####接着进入 sqlite 数据库
sqlite3 familyGuy.db

####查看都有哪些数据库
.database

####接着查看表
select * from myTable;

####再做简单的筛选
select * from myTable where FirstName = 'Peter';

###############################
注意 sql 语法 和mysql  oracle 都是一样的 
都是关系型数据库

############################################

文章来源:https://blog.csdn.net/ttxiaoxiaobai/article/details/135619460
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。