C++和Python在数据库操作中的协作可以通过多种方式实现。以下是一些常见的方法:
C++后端:
// C++后端示例(使用SQLite)
#include <sqlite3.h>
#include <iostream>
static int callback(void* data, int argc, char** argv, char** azColName) {
for (int i = 0; i < argc; i++) {
std::cout << azColName[i] << ": " << (argv[i] ? argv[i] : "NULL") << std::endl;
}
std::cout << std::endl;
return 0;
}
int main() {
sqlite3* db;
char* errorMessage = nullptr;
int exitcode = sqlite3_open("example.db", &db);
if (exitcode) {
std::cerr << "Can't open database: " << sqlite3_errmsg(db) << std::endl;
return exitcode;
}
const char* sql = "SELECT * FROM users;";
exitcode = sqlite3_exec(db, sql, callback, nullptr, &errorMessage);
if (exitcode != SQLITE_OK) {
std::cerr << "SQL error: " << errorMessage << std::endl;
sqlite3_free(errorMessage);
}
sqlite3_close(db);
return 0;
}
Python前端:
requests
库或sqlite3
库与C++后端通信。# Python前端示例
import requests
def get_users():
response = requests.get('http://localhost:8080/api/users')
if response.status_code == 200:
users = response.json()
print(users)
else:
print("Failed to get users")
if __name__ == "__main__":
get_users()
C++数据库驱动:
// C++数据库驱动示例(使用SQLite)
#include <sqlite3.h>
#include <iostream>
static int callback(void* data, int argc, char** argv, char** azColName) {
for (int i = 0; i < argc; i++) {
std::cout << azColName[i] << ": " << (argv[i] ? argv[i] : "NULL") << std::endl;
}
std::cout << std::endl;
return 0;
}
void create_table() {
sqlite3* db;
char* errorMessage = nullptr;
int exitcode = sqlite3_open("example.db", &db);
if (exitcode) {
std::cerr << "Can't open database: " << sqlite3_errmsg(db) << std::endl;
return;
}
const char* sql = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT);";
exitcode = sqlite3_exec(db, sql, callback, nullptr, &errorMessage);
if (exitcode != SQLITE_OK) {
std::cerr << "SQL error: " << errorMessage << std::endl;
sqlite3_free(errorMessage);
}
sqlite3_close(db);
}
void insert_user(const std::string& name, const std::string& email) {
sqlite3* db;
char* errorMessage = nullptr;
int exitcode = sqlite3_open("example.db", &db);
if (exitcode) {
std::cerr << "Can't open database: " << sqlite3_errmsg(db) << std::endl;
return;
}
const char* sql = "INSERT INTO users (name, email) VALUES (?, ?);";
sqlite3_stmt* stmt;
exitcode = sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr);
if (exitcode != SQLITE_OK) {
std::cerr << "SQL error: " << sqlite3_errmsg(db) << std::endl;
sqlite3_close(db);
return;
}
sqlite3_bind_text(stmt, 1, name.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, email.c_str(), -1, SQLITE_STATIC);
exitcode = sqlite3_step(stmt);
if (exitcode != SQLITE_DONE) {
std::cerr << "SQL error: " << sqlite3_errmsg(db) << std::endl;
}
sqlite3_finalize(stmt);
sqlite3_close(db);
}
void get_users() {
sqlite3* db;
char* errorMessage = nullptr;
int exitcode = sqlite3_open("example.db", &db);
if (exitcode) {
std::cerr << "Can't open database: " << sqlite3_errmsg(db) << std::endl;
return;
}
const char* sql = "SELECT * FROM users;";
exitcode = sqlite3_exec(db, sql, callback, nullptr, &errorMessage);
if (exitcode != SQLITE_OK) {
std::cerr << "SQL error: " << errorMessage << std::endl;
sqlite3_free(errorMessage);
}
sqlite3_close(db);
}
Python应用逻辑:
# Python应用逻辑示例
import sqlite3
def create_table():
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT);''')
conn.commit()
conn.close()
def insert_user(name, email):
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", (name, email))
conn.commit()
conn.close()
def get_users():
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM users;")
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close()
if __name__ == "__main__":
create_table()
insert_user("John Doe", "john@example.com")
get_users()
C++数据库连接池:
// C++数据库连接池示例(使用SQLite)
#include <sqlite3.h>
#include <iostream>
#include <queue>
#include <mutex>
#include <condition_variable>
class SQLiteConnectionPool {
public:
SQLiteConnectionPool(const std::string& db_name, int pool_size) {
for (int i = 0; i < pool_size; ++i) {
connections.emplace(std::make_shared<SQLiteConnection>(db_name));
}
}
std::shared_ptr<SQLiteConnection> acquire() {
std::unique_lock<std::mutex> lock(mtx);
cond.wait(lock, [this] { return !connections.empty(); });
auto conn = connections.front();
connections.pop();
return conn;
}
void release(std::shared_ptr<SQLiteConnection> conn) {
std::unique_lock<std::mutex> lock(mtx);
connections.push(conn);
lock.unlock();
cond.notify_one();
}
private:
struct SQLiteConnection {
SQLiteConnection(const std::string& db_name) {
int exitcode = sqlite3_open(db_name.c_str(), &db);
if (exitcode) {
std::cerr << "Can't open database: " << sqlite3_errmsg(db) << std::endl;
}
}
~SQLiteConnection() {
sqlite3_close(db);
}
sqlite3* db;
};
std::queue<std::shared_ptr<SQLiteConnection>> connections;
std::mutex mtx;
std::condition_variable cond;
};
void execute_query(std::shared_ptr<SQLiteConnection> conn, const std::string& query) {
char* errorMessage = nullptr;
int exitcode = sqlite3_exec(conn->db, query.c_str(), callback, nullptr, &errorMessage);
if (exitcode != SQLITE_OK) {
std::cerr << "SQL error: " << errorMessage << std::endl;
sqlite3_free(errorMessage);
}
}
int callback(void* data, int argc, char** argv, char** azColName) {
for (int i = 0; i < argc; i++) {
std::cout << azColName[i] << ": " << (argv[i] ? argv[i] : "NULL") << std::endl;
}
std::cout << std::endl;
return 0;
}
Python应用逻辑:
# Python应用逻辑示例
import sqlite3
class SQLiteConnectionPool:
def __init__(self, db_name, pool_size):
self.pool = []
for _ in range(pool_size):
conn = sqlite3.connect(db_name)
self.pool.append(conn)
def acquire(self):
if not self.pool:
raise Exception("No available connections in the pool")
return self.pool.pop()
def release(self, conn):
self.pool.append(conn)
def execute_query(query):
conn = pool.acquire()
try:
cursor = conn.cursor()
cursor.execute(query)
result = cursor.fetchall()
for row in result:
print(row)
finally:
pool.release(conn)
if __name__ == "__main__":
pool = SQLiteConnectionPool('example.db', 10)
execute_query("SELECT * FROM users;")
通过以上几种方法,C++和Python可以在数据库操作中进行有效的协作。选择哪种方法取决于具体的应用场景和需求。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。