windows下连接mysql

在Windows下连接MySQL时,可能会遇到WinSock2.h包含顺序、句柄重复使用和未调用mysql_init()导致的问题。确保WinSock2.h在windows.h之前,避免句柄错误,使用清除内存函数解决遗留连接,且在调用mysql_real_connect()前必须调用mysql_init()以防止各种问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <WinSock2.h>
#include <mysql.h>
#include <windows.h>

void *thread_fun(void *);

int  main()
{
	pthread_t thread_id[10];
	int i;
	//MYSQL mysql;
	//if(mysql_init(&mysql)==NULL)
	//	return -1;



	for( i = 0; i < 10; i++)
	{

		pthread_create(&thread_id[i], NULL, thread_fun, NULL);
	}
	for(i = 0; i <  10 ; i++)
	{
		pthread_join(thread_id[i], NULL);
	}

	return 0;

}

void *thread_fun(void *ptr)
{

	MYSQL mysql;   

	MYSQL_RES * result;                        
	MYSQL_ROW row;                               

	const char * host = "localhost";  
	const char * user = "root";       
	const char * passwd = "123456"; 
	const char * db = "testmysql";                 

	if(mysql_init(&mysql)==NULL)
		exit(1);

	mysql_thread_init();  

                      
	if (  mysql_real_connect(&mysql, "localhost", "root", "123456", "testmysql", 3306, NULL, 0)  == NULL ) 
	{ 
		printf("connect error: \n"); 
		fprintf(stderr, " %s\n", mysql_error(&mysql)); 
		exit(1); 
	} 
	else 
	{ 
		fprintf(stderr, "connect success.\n"); 
	} 

	const char * i_query = "select * from children";

	if ( mysql_query(&mysql, i_query) != 0 )      
	{ 
		fprintf(stderr, "query error.\n"); 
		exit(1); 
	} 
	else 
	{ 
		if ( (result = mysql_store_result(&mysql)) == NULL )
        { 
                fprintf(stderr, "store error.\n"); 
                exit(1); 
        } 
        else 
        { 
		while ( (row = mysql_fetch_row(result)) != NULL ) 
		{ 
			printf("id is %s\t",row[0]);
			printf("name is %s\t", row[1]);              
			printf("age is %s\t\n", row[2]);              
		}
        } 
 
    } 

	mysql_close(&mysql);
	mysql_free_result(result);					
	mysql_thread_end();
	return ((void *)0);
}


需要注意的事项:

1:WinSock2.h需要放在windows.h前面,否则有可能出现问题。  

2:有可能弹出this handle is already connected。Use separate handle foreach connection的错误,提示说,这个句柄已经连接用掉了,其他的连接需要用

 其他的的句柄。(我认为,pthread_create()函数调用了10次thread_fun(),thread_fun()中每次都重新建立连接,断开连接了,这里应该不会出错。直到现在,我还

不知道这个想法到底是错是对)。但是这个错误是:因为以前内存中存在其他的连接而造成的,所以用清除内存函数,清除一下 MYSQL句柄,就行了。以后就不会出现这个问

题了。

3:第三个特别需要注意的事项:调用mysql_real_conect()函数之前一定要调用mysql_init(),否则会出现各种各样的问题。(而在main函数中是否在调用一     次MYSQL 

mysql;mysql_init()。调用不调用都不会出错。为什么这样,不太清楚)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值