简单的实现增删查改的操作后,实现了一个先读写其中一个表的某两项内容,再把相关字符段写入到另外一张表中去。涉及到查询和插入两个步骤。
其中还涉及到汉字的读写和插入,会有字符的操作产生乱码。所以要先保证mysql的汉字字符编码,linux终端字符编码都是统一的。
/*** QueryAndInsert ***/ #include<stdio.h> #include<string.h> #include<stdlib.h> #include"mysql.h"int main() {printf("version = 1.0\n");MYSQL mysql;MYSQL_RES * res;MYSQL_ROW row;int r;char* query;char taskID[256],taskName[256];char insert[256];int flag;mysql_init(&mysql);//mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "gdk");if(!mysql_real_connect(&mysql,"localhost","root","mysql123","csql",0,NULL,0)){printf("Can't connect the mysql ! errInfo = [ %s ] ",mysql_error(&mysql));}else{//query partprintf("connect the mysql successfully! \n");query = "select taskID,taskName from task where taskState=4 order by taskLastEditTime desc";mysql_query(&mysql, "set names utf8");flag = mysql_real_query(&mysql,query,(unsigned int )strlen(query));if(flag){printf("query failed\n");return 0;}else{printf("[%s] made....\n",query);res = mysql_store_result(&mysql);while(row = mysql_fetch_row(res)){ sprintf(taskID,"%s",row[0]);sprintf(taskName,"%s",row[1]);}}}printf("taskID = %s, taskName = %s\n",taskID,taskName);sprintf(insert,"insert into EnvironmentRealData (TaskID,taskName) values(\'%s\',\'%s\');",taskID,taskName);printf("insert = %s\n",insert);
//insertif(mysql_real_query(&mysql,insert,(unsigned int)strlen(insert))){printf("insert data is faile\n");return 0;}else{printf("Insert successfully\n");}mysql_close(&mysql);return 0; }
gcc编译:gcc QueryAndInsert.c -o QueryAndInsert -I /usr/inlcude/mysql -L /usr/lib/mysql -lmysqlclient