c++ 实现对mysql数据的操作 给出详细示例
时间: 2024-03-20 08:43:30 浏览: 14
以下是一个简单的 C++ 程序,用于连接 MySQL 数据库并执行查询操作:
```cpp
#include <mysql.h>
#include <iostream>
#include <string>
using namespace std;
int main() {
MYSQL* conn = mysql_init(NULL);
if (conn == NULL) {
cout << "Error: can't create MySQL-descriptor" << endl;
return 1;
}
string host = "localhost";
string user = "root";
string password = "123456";
string database = "mydb";
unsigned int port = 3306;
if (!mysql_real_connect(conn, host.c_str(), user.c_str(), password.c_str(), database.c_str(), port, NULL, 0)) {
cout << "Error: can't connect to MySQL server" << endl;
return 1;
}
string query = "SELECT * FROM mytable";
if (mysql_query(conn, query.c_str())) {
cout << "Error: can't execute query" << endl;
return 1;
}
MYSQL_RES* result = mysql_store_result(conn);
if (result == NULL) {
cout << "Error: can't get result set" << endl;
return 1;
}
int num_fields = mysql_num_fields(result);
MYSQL_ROW row;
while ((row = mysql_fetch_row(result))) {
for (int i = 0; i < num_fields; i++) {
cout << row[i] << "\t";
}
cout << endl;
}
mysql_free_result(result);
mysql_close(conn);
return 0;
}
```
这个程序连接到本地 MySQL 服务器,使用用户名 "root" 和密码 "123456" 访问名为 "mydb" 的数据库,并执行一个查询操作,从名为 "mytable" 的表中检索所有行。最后,程序打印出结果集中的每一行。
请注意,为了编译这个程序,您需要在编译器命令行中添加以下选项:
```
-lmysqlclient
```
这个选项告诉编译器链接 MySQL 客户端库。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)