C++在Ubuntu上如何进行数据库连接
导读:在Ubuntu上使用C++连接数据库,通常需要使用数据库提供的客户端库。以下是一些常见数据库的连接方法: 1. MySQL 安装MySQL客户端库 sudo apt-get update sudo apt-get install libmy...
在Ubuntu上使用C++连接数据库,通常需要使用数据库提供的客户端库。以下是一些常见数据库的连接方法:
1. MySQL
安装MySQL客户端库
sudo apt-get update
sudo apt-get install libmysqlclient-dev
示例代码
#include <
mysql/mysql.h>
#include <
iostream>
int main() {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
conn = mysql_init(NULL);
// 连接到数据库
if (!mysql_real_connect(conn, "localhost", "user", "password", "database", 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
// 执行SQL查询
if (mysql_query(conn, "SELECT * FROM table_name")) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res = mysql_use_result(conn);
// 处理查询结果
while ((row = mysql_fetch_row(res)) != NULL) {
std::cout <
<
row[0] <
<
" " <
<
row[1] <
<
std::endl;
}
// 释放资源
mysql_free_result(res);
mysql_close(conn);
return 0;
}
2. PostgreSQL
安装PostgreSQL客户端库
sudo apt-get update
sudo apt-get install libpq-dev
示例代码
#include <
libpq-fe.h>
#include <
iostream>
int main() {
PGconn *conn;
PGresult *res;
conn = PQconnectdb("host=localhost dbname=database user=user password=password");
if (PQstatus(conn) != CONNECTION_OK) {
std::cerr <
<
"Connection to database failed: " <
<
PQerrorMessage(conn) <
<
std::endl;
PQfinish(conn);
exit(1);
}
res = PQexec(conn, "SELECT * FROM table_name");
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
std::cerr <
<
"SELECT failed: " <
<
PQerrorMessage(conn) <
<
std::endl;
PQclear(res);
PQfinish(conn);
exit(1);
}
int rows = PQntuples(res);
for (int i = 0;
i <
rows;
i++) {
std::cout <
<
PQgetvalue(res, i, 0) <
<
" " <
<
PQgetvalue(res, i, 1) <
<
std::endl;
}
PQclear(res);
PQfinish(conn);
return 0;
}
3. SQLite
安装SQLite3
sudo apt-get update
sudo apt-get install libsqlite3-dev
示例代码
#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 *err_msg = 0;
int rc;
rc = sqlite3_open("test.db", &
db);
if (rc != SQLITE_OK) {
std::cerr <
<
"Cannot open database: " <
<
sqlite3_errmsg(db) <
<
std::endl;
sqlite3_close(db);
return 1;
}
rc = sqlite3_exec(db, "SELECT * FROM table_name", callback, 0, &
err_msg);
if (rc != SQLITE_OK) {
std::cerr <
<
"SQL error: " <
<
err_msg <
<
std::endl;
sqlite3_free(err_msg);
sqlite3_close(db);
return 1;
}
sqlite3_close(db);
return 0;
}
编译和运行
对于上述示例代码,你可以使用以下命令进行编译:
MySQL
g++ -o mysql_example mysql_example.cpp -lmysqlclient
./mysql_example
PostgreSQL
g++ -o postgres_example postgres_example.cpp -lpq
./postgres_example
SQLite
g++ -o sqlite_example sqlite_example.cpp -lsqlite3
./sqlite_example
确保你已经安装了相应的数据库服务器,并且数据库和表已经创建好。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: C++在Ubuntu上如何进行数据库连接
本文地址: https://pptw.com/jishu/720092.html