您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。