在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。