在C++中,有多种方法可以用于连接数据库。以下是一些常用的库和方法:
#include <mysqlx/xdevapi.h>
int main() {
try {
mysqlx::Session session("localhost", 33060, "username", "password");
std::cout << "Connected to database successfully!" << std::endl;
} catch (const mysqlx::Error &err) {
std::cerr << "Error: " << err.what() << std::endl;
return 1;
}
return 0;
}
#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("test.db", &db);
if (exitcode) {
std::cerr << "Can't open database: " << sqlite3_errmsg(db) << std::endl;
return exitcode;
}
std::string sql = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, name TEXT)";
exitcode = sqlite3_exec(db, sql.c_str(), callback, nullptr, &errorMessage);
if (exitcode != SQLITE_OK) {
std::cerr << "SQL error: " << errorMessage << std::endl;
sqlite3_free(errorMessage);
} else {
sql = "INSERT INTO test (name) VALUES ('John Doe')";
exitcode = sqlite3_exec(db, sql.c_str(), callback, nullptr, &errorMessage);
if (exitcode != SQLITE_OK) {
std::cerr << "SQL error: " << errorMessage << std::endl;
sqlite3_free(errorMessage);
}
}
sqlite3_close(db);
return 0;
}
#include <iostream>
#include <pqxx/pqxx>
int main() {
try {
pqxx::connection conn("dbname=test user=username password=password host=localhost port=5432");
std::cout << "Connected to database successfully!" << std::endl;
pqxx::work txn(conn);
txn.exec("CREATE TABLE IF NOT EXISTS test (id SERIAL PRIMARY KEY, name TEXT)");
txn.exec("INSERT INTO test (name) VALUES ('John Doe')");
txn.commit();
} catch (const pqxx::pqxx_exception &e) {
std::cerr << "Error: " << e.base().what() << std::endl;
return 1;
}
return 0;
}
这些只是C++中连接数据库的一些方法。根据你的需求和项目规模,可以选择最适合你的库和方法。