C++ 连接Mysql数据库
1,安装mysql数据库
关于远程访问问题的一些解决方法:
会出现如下错误“ERROR 2003 (HY000): Can't connect to MySQL server on '192.168.137.100' (10061)”
#my.ini 配置文件 #bind-address = 127.0.0.1 <---注释掉这一行
”ERROR 1130 (HY000): Host 'abbuggy-PC.mshome.net' is not allowed to connect to this MySQL server“
grant all privileges on *.* to root@"%" identified by 'sql5' with grant option; flush privileges;
可参考:http://blog.csdn.net/abbuggy/article/details/8272432
2.需要安装mysql后的三个文件mysql.h libmysql.lib libmysql.dll 。
#include<Windows.h> #include<stdio.h> /*#include<WinSock.h>*/ #include <mysql.h> int main() { MYSQL *con = mysql_init((MYSQL *)0); MYSQL_RES *res; MYSQL_ROW row; char tmp[400]; //database configuartion char dbuser[30] = "root"; char dbpasswd[30] = ""; char dbip[30] = "127.0.0.1"; char dbname[50]="mysql"; char tablename[50]="test"; char *query=NULL; int x; int y; int rt; unsigned int t; int count = 0; printf("input x,y\n"); scanf("%d,%d", &x,&y); fflush(stdin); printf("input ouver\n"); con = mysql_init(0); //第一步初始化 if(con!=NULL&&mysql_real_connect(con,dbip,dbuser,dbpasswd,dbname,3306,NULL,0)) //第二步连接数据库 { if (!mysql_select_db(con,dbname)) //第三步选择数据库 { con->reconnect = 1; query = "SELECT * FROM user"; if (rt = mysql_real_query(con,query,strlen(query))) //第四步执行命令 { query = ""; } else { res = mysql_store_result(con); //第五步获取返回结果 while(row = mysql_fetch_row(res)) { for (t=0;t<mysql_num_fields(res);t++) { printf("%s ",row[t]); } } } } } }