您好,登錄后才能下訂單哦!
在C++中,有多種方法可以與數據庫進行交互
#include <sqlite3.h>
#include <iostream>
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 = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)";
exitcode = sqlite3_exec(db, sql, nullptr, nullptr, &errorMessage);
if (exitcode != SQLITE_OK) {
std::cerr << "SQL error: " << errorMessage << std::endl;
sqlite3_free(errorMessage);
} else {
std::cout << "Table created successfully" << std::endl;
}
sql = "INSERT INTO users (name) VALUES ('John Doe')";
exitcode = sqlite3_exec(db, sql, nullptr, nullptr, &errorMessage);
if (exitcode != SQLITE_OK) {
std::cerr << "SQL error: " << errorMessage << std::endl;
sqlite3_free(errorMessage);
} else {
std::cout << "Record inserted successfully" << std::endl;
}
sqlite3_close(db);
return 0;
}
#include <mysqlx/xdevapi.h>
#include <iostream>
int main() {
try {
mysqlx::Session session("localhost", 33060, "username", "password", "database");
mysqlx::Schema schema = session.getSchema("database");
mysqlx::Table table = schema.getTable("users");
mysqlx::RowResult result = table.insertOne("John Doe");
std::cout << "Record inserted successfully, ID: " << result[0].getValue("id") << std::endl;
} catch (const mysqlx::Error& err) {
std::cerr << "Error: " << err.what() << std::endl;
}
return 0;
}
#include <iostream>
#include <pqxx/pqxx>
int main() {
try {
pqxx::connection conn("dbname=database user=username password=password host=localhost port=5432");
pqxx::work txn(conn);
pqxx::result result = txn.exec("CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name TEXT)");
txn.commit();
result = txn.exec("INSERT INTO users (name) VALUES ('John Doe')");
txn.commit();
std::cout << "Record inserted successfully, ID: " << result[0][0].c_str() << std::endl;
} catch (const pqxx::Error& err) {
std::cerr << "Error: " << err.what() << std::endl;
}
return 0;
}
這些示例展示了如何在C++中使用不同的庫與數據庫進行交互。根據項目需求和數據庫類型,可以選擇合適的庫進行操作。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。