C连接Mysql数据库代码

时间:2021-12-23 07:19:26

复制代码 代码如下:

//vc工具中添加E:\WAMP\BIN\MYSQL\MYSQL5.5.8\LIB 路径 
 //在工程设置-》链接》库模块中添加 libmysql.lib  
#include <stdio.h> 
#include <time.h> 
#include <string.h> 
#include <winsock.h> 
#include "E:\wamp\bin\mysql\mysql5.5.8\include\mysql.h" 
void main(){  
       MYSQL *conn;  
       MYSQL_RES *res;  
       MYSQL_ROW row;  
       char *server ="localhost";  
       char *user ="root";  
       char *password="";  
       char *database="test";  
       char sql[1024]="select * from chinaren";  
       conn=mysql_init(NULL);  

       if(!mysql_real_connect(conn,server,user,password,database,0,NULL,0)){  
               fprintf(stderr,"%s\n",mysql_error(conn));  
               exit(1);  
       }  

       if(mysql_query(conn,sql)){  
               fprintf(stderr,"%s\n",mysql_error(conn));  
               exit(1);  
       }  

       res=mysql_use_result(conn);  

       while((row = mysql_fetch_row(res))!=NULL){  
               printf("%s\n",row[2]);  
       }  

       mysql_free_result(res);  
       mysql_close(conn);  
}