首先需要下载mysql server,并安装,安装好之后,把include和lib设置一下。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
#include <windows.h> #include <stdio.h> #include <mysql.h> #pragma comment(lib, "libmysql.lib") int main() { unsigned short Port = 3306; char *IPAddress = "114.112.90.57"; char *UserName = "user"; char *Password = "123"; char *DBName = "mobile"; unsigned long i; printf("Start... \n"); MYSQL *ssock; MYSQL_RES *res; MYSQL_ROW row; //char execsql[500]; ssock = (MYSQL *)malloc(sizeof(MYSQL)); //在某些版本中,不需要该初始化工作,可观看mysql.H以及readme mysql_init(ssock); if(ssock == NULL) { printf("EROR: MySQL ssock init error. \n"); return FALSE; } printf("MySQL ssock init OK. \n"); //连接到指定的数据库 ssock = mysql_real_connect(ssock, IPAddress, UserName, Password, NULL, Port, NULL, 0); if(!ssock) { printf("conn fail... \n"); //memcpy(eee, mysql_error(ssock), 20); //fprintf(stderr, "Failed to connect to database: Error: %s ", mysql_error(ssock)); //printf("%c ", eee); unsigned int mtint = mysql_errno(ssock); //printf("%d "); return FALSE; } printf("MySQL connnect OK... \n"); if(mysql_select_db(ssock, DBName) != 0) { printf("select db error. \n"); return FALSE; } printf("select db OK. \n"); printf("version=%d \n", mysql_get_server_version(ssock)); //SQL查询语句 if(mysql_query( ssock,"SELECT * FROM UserInfo")) { printf("mysql_query() Error, %s\n", mysql_error(ssock)); } if( !(res = mysql_store_result(ssock)) ) { printf("mysql_store_result() Error, %s\n", mysql_error(ssock)); } while( (row = mysql_fetch_row(res)) ) { for(i=0 ; i<mysql_num_fields(res); i++) { printf("%s ",row[i]); } printf("\n"); } mysql_free_result(res); //执行SQL插入语句,第一列自增 if(mysql_query( ssock,"insert into UserInfo SET userName=\'lmy4\', userLogName=\'lmy4\', userLogPWD=\'000000\', userRole=1,userState=0 " )) { printf("mysql_query() Error, %s\n", mysql_error(ssock)); } mysql_close(ssock); printf("End... \n"); getchar(); return TRUE; } |
转载请注明:exchen's blog » VC操作MySQL数据库