windows下连接mysql

来源:互联网 发布:软件测试有哪些 编辑:程序博客网 时间:2024/05/23 15:26
#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()。调用不调用都不会出错。为什么这样,不太清楚)。

原创粉丝点击