MySQL连接到C++

纠结了两天,终于实现了使用MySQL API C 函数连接到了C++,方法如下:
首先,电脑室64位的操作系统,下载的MySQL也是64位的;在vs下创建一个工程(win32控制台程序),命名为mysql;接下来进行环境配置
在解决方案资源管理器中右击mysql,选择属性。
1、C/C++>常规>附加包含目录,在附加包含目录中添加MySQL中include的路径,例如,我选择的是C:\Program Files\MySQL\MySQL Server 5.5\include;
2、连接器> 常规>附加包含目录,在附加包含目录中添加MySQL中lib的路径,例如,我选择的是C:\Program Files\MySQL\MySQL Server 5.5\lib;
3、连接器>输入>附加依赖项,在其中添加libmysql.lib;
4、然后点击配置管理器>平台>新建>新建平台中选择 X64;
5、再把MySQL安装目录中lib文件夹下的libmyql.dll拷贝到所建工程的文件中;

环境配置完成,然后是测试,测试代码来源于网上的博客。

#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql.h>
#include <iostream>
#include <tchar.h>
#pragma comment(lib,"libmysql.lib")
using namespace std;

int main()
{
	const char user[] = "root";
	const char pswd[] = "123456";//数据库密码
	const char host[] = "localhost";
	const char database[] = "mydata";//数据库名称
	unsigned int port = 3306;
	MYSQL myCont;
	MYSQL_RES *result = NULL;
	MYSQL_ROW sql_row;
	MYSQL_FIELD *fd;
	char column[32][32];
	int res;
	mysql_init(&myCont);
	if (mysql_real_connect(&myCont, host, user, pswd, database, port, NULL, 0))
	{
		cout << "connect succeed!" << endl;
		mysql_query(&myCont, "SET NAMES latin1");
		res = mysql_query(&myCont, "select * from shop");// shop为表的名字
		if (!res)
		{
			result = mysql_store_result(&myCont);
			if (result)
			{
				int i, j;
				cout << "number of result: " << (unsigned long)mysql_num_rows(result) << endl;
				for (i = 0; fd = mysql_fetch_field(result); i++)//获取列名  
				{
					strcpy_s(column[i], fd->name);
				}
				j = mysql_num_fields(result);
				for (i = 0; i<j; i++)
				{
					printf("%s\t", column[i]);
				}
				printf("\n");
				while (sql_row = mysql_fetch_row(result))//获取具体的数据  
				{
					for (i = 0; i<j; i++)
					{
						printf("%s\t\t", sql_row[i]);
					}
					printf("\n");
				}
			}
		}
		else
		{
			cout << "query sql failed!" << endl;
		}
	}
	else
	{
		cout << "connect failed!" << endl;
	}
	if (result != NULL)
	{
		mysql_free_result(result);
		mysql_close(&myCont);
	}
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值