C++利用Sqlite3创建两个表
时间: 2023-11-22 18:54:53 浏览: 88
C++ Sqlite3的使用方法
好的,以下是利用C++和SQLite3创建两个表的示例代码:
```cpp
#include <iostream>
#include <sqlite3.h>
using namespace std;
int main() {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
// 打开数据库
rc = sqlite3_open("example.db", &db);
if (rc) {
cerr << "Can't open database: " << sqlite3_errmsg(db) << endl;
return(0);
} else {
cout << "Opened database successfully" << endl;
}
// 创建表1
const char *sql1 = "CREATE TABLE COMPANY("
"ID INT PRIMARY KEY NOT NULL,"
"NAME TEXT NOT NULL,"
"AGE INT NOT NULL,"
"ADDRESS CHAR(50),"
"SALARY REAL);";
rc = sqlite3_exec(db, sql1, 0, 0, &zErrMsg);
if (rc != SQLITE_OK) {
cerr << "SQL error: " << zErrMsg << endl;
sqlite3_free(zErrMsg);
} else {
cout << "Table COMPANY created successfully" << endl;
}
// 创建表2
const char *sql2 = "CREATE TABLE DEPARTMENT("
"ID INT PRIMARY KEY NOT NULL,"
"DEPT CHAR(50) NOT NULL,"
"EMP_ID INT NOT NULL);";
rc = sqlite3_exec(db, sql2, 0, 0, &zErrMsg);
if (rc != SQLITE_OK) {
cerr << "SQL error: " << zErrMsg << endl;
sqlite3_free(zErrMsg);
} else {
cout << "Table DEPARTMENT created successfully" << endl;
}
// 关闭数据库
sqlite3_close(db);
return(0);
}
```
这段代码使用了SQLite3数据库,通过`sqlite3_open()`函数打开了一个名为`example.db`的数据库文件。然后,通过`sqlite3_exec()`函数执行两个CREATE TABLE语句来创建两个表,分别是COMPANY和DEPARTMENT。最后,通过`sqlite3_close()`函数关闭了数据库连接。
需要注意的是,SQLite3支持的数据类型比较简单,例如TEXT、INT、REAL等,可以根据需要来选择适合的数据类型。同时,上面代码没有进行异常处理,实际应用中需要加入更多的错误处理和安全性检查。
阅读全文