c和vs连接mysql代码
时间: 2023-09-18 19:06:45 浏览: 84
以下是使用 C 和 Visual Studio 连接 MySQL 数据库的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <mysql.h>
#pragma comment(lib, "libmysql.lib")
#pragma comment(lib, "ws2_32.lib")
int main()
{
MYSQL mysql;
MYSQL_RES *res;
MYSQL_ROW row;
char query[200];
mysql_init(&mysql);
// 连接 MySQL 服务器
if (!mysql_real_connect(&mysql, "localhost", "root", "password", "database_name", 3306, NULL, 0))
{
printf("无法连接到MySQL服务器: %s\n", mysql_error(&mysql));
return 1;
}
// 执行 SQL 查询
sprintf(query, "SELECT * FROM table_name");
if (mysql_query(&mysql, query))
{
printf("查询失败: %s\n", mysql_error(&mysql));
return 1;
}
// 处理查询结果
res = mysql_store_result(&mysql);
while (row = mysql_fetch_row(res))
{
printf("%s\t%s\n", row[0], row[1]);
}
// 释放资源
mysql_free_result(res);
mysql_close(&mysql);
return 0;
}
```
在代码中,需要将 `localhost`、`root`、`password`、`database_name` 和 `table_name` 替换成实际的 MySQL 服务器地址、用户名、密码、数据库名和表名。建议先在 MySQL 客户端测试 SQL 查询语句是否正确,再将其复制到代码中。
阅读全文
相关推荐













