日期:2014-05-16  浏览次数:20468 次

多进程插入mysql数据库
如何编译?
gcc -Wall -o a.out $(mysql_config --cflags) mysql_insert.c $(mysql_config --libs)
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include <mysql/mysql.h>
#include<sys/types.h>
#include<sys/wait.h>

#define DB_HOST "127.0.0.1"
#define DB_USER "root"
#define DB_PASS ""
#define DB_NAME "test"
#define DB_PORT 3307

int main(int argc, char **argv)
{
	MYSQL mysql;

	unsigned int i;
	int rtn; /*子进程的返回数值*/
	unsigned int process_no;
	unsigned int userId;
	unsigned int type;
	unsigned int itemCate;
	unsigned int itemType;
	unsigned int itemNum;
	unsigned int totalCost;
	unsigned int consumeTime;
	unsigned int leftBalance;
	char itemName[1000] ;
	char sql[20000] ;

    struct timeval time_start,time_end;
    float execute_time;
	
    //srand(time(0));

	for(process_no = 1; process_no < 18; process_no++)
	{
		if(fork() == 0)
		{
		    // 开始执行时间
		    gettimeofday(&time_start,NULL);

			mysql_init(&mysql);

			if(!mysql_real_connect(&mysql,DB_HOST,DB_USER,DB_PASS,DB_NAME,DB_PORT,NULL,0))
			{
				fprintf(stderr, "Failed to connect to database: Error: %s\n",mysql_error(&mysql));
			}

			mysql_query(&mysql,"SET NAMES utf8");

			for(i = 0; i < 444444; i++)
			{
				sprintf(itemName,"%s","");

				userId = rand()%19071388 + 1;
				type = rand()%4 + 1;
				itemCate = rand()%15 + 1;
				itemType = rand()%100 + 1;
				itemNum = rand()%100 + 1;
				totalCost = rand()%10000 + 1;
				consumeTime = rand()%1309120853 + 1;
				leftBalance = rand()%10000 + 1;

				sprintf(sql,"insert into user_consume1(userId,type,itemCate,itemType,itemNum,totalCost,consumeTime,leftBalance,itemName)values(%d,%d,%d,%d,%d,%d,%d,%d,'')",
					userId,type,itemCate,itemType,itemNum,totalCost,consumeTime,leftBalance);

				if(mysql_query(&mysql,sql))
				{
					fprintf(stderr,"query failed:%s",mysql_error(&mysql));
				}
			}

			mysql_close(&mysql);

			// 结束执行时间
			gettimeofday(&time_end,NULL);

			execute_time = (time_end.tv_sec - time_start.tv_sec) + (time_end.tv_usec - time_start.tv_usec)/1000000;
			printf("execute time:%f\n",execute_time);

			exit(0);
		}
		else
		{
			/* 父进程, 等待子进程结束,并打印子进程的返回值 */
			//wait ( &rtn );
			//printf("child process return %d\n",rtn);
			//return 0;
			//printf("execute child process return %d\n",process_no);
		}
	}

	return 0;
}