MySQL数据表中插入数据并查询输出的实现

 2022-10-27    311  

MySQL数据表中插入数据是我们很常见的操作,下面就为您详细介绍MySQL数据表中插入数据并查询输出的实现方法步骤,如果您对MySQL数据表方面感兴趣的话,不妨一看。

CREATETABLEdemotable( 
idint(11)NOTNULLauto_increment, 
demodatavarchar(255)defaultNULL, 
PRIMARYKEY(id) 
)TYPE=MyISAM; 

----------往数据表中插入数据并查询输出---------- 
#include<mysql.h>/*HeadersforMySQLusage*/ 
#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 

intmain(intargc,char**argv){ 
MYSQLdemo_db; 
mysql_init(&demo_db); 

intinsert_id; 
char*encdata,*query; 
intdatasize; 
MYSQL_RES*res;/*Tobeusedtofetchinformationinto*/ 
MYSQL_ROWrow; 

if(argc<2){ 
printf("Pleasesupplyastringforinsertionintothedatabase\n"); 
exit(0); 
} 

if(!mysql_real_connect(&demo_db,"localhost","root","mysql","demodb",0,NULL,0)){ 
printf(mysql_error(&demo_db)); 
exit(1); 
} 

//if(mysql_select_db(&demo_db,"demodb")){/*Selectthedatabasewewanttouse*/ 
//printf(mysql_error(&demo_db)); 
//exit(1); 
//} 

encdata=malloc(2*strlen(argv[1])+1); 

datasize=mysql_real_escape_string(&demo_db,encdata,argv[1],strlen(argv[1])); 
//printf("%s\n",encdata); 

query=malloc(datasize+255); 
sprintf(query,"INSERTINTOdemotable(demodata)VALUES('%s')",encdata);/*Buildquery*/ 
//printf("%s\n",query); 

if(mysql_real_query(&demo_db,query,strlen(query))){/*Makequery*/ 
printf(mysql_error(&demo_db)); 
exit(1); 
} 
free(query); 

insert_id=mysql_insert_id(&demo_db);/*Findwhatidthatdatawasgiven*/ 

query=malloc(255); 
sprintf(query,"SELECTdemodataFROMdemotableWHEREid=%d",insert_id); 
if(mysql_real_query(&demo_db,query,strlen(query))){/*Makequery*/ 
printf(mysql_error(&demo_db)); 
exit(1); 
} 
free(query); 

res=mysql_store_result(&demo_db);/*Downloadresultfromserver*/ 
row=mysql_fetch_row(res);/*Getarowfromtheresults*/ 
printf("Youinserted\"%s\".\n",row[0]); 
mysql_free_result(res);/*Releasememoryusedtostoreresults.*/ 
mysql_close(&demo_db); 

return0; 
} 


MySQL数据表中插入数据并查询输出的实现

  •  标签:  
  • MySQL
  •  

原文链接:https://77isp.com/post/4493.html

=========================================

https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。