linux c mysql demo

#include <stdio.h>
#include "/usr/local/mysql/include/mysql.h"
int main(int argc,char *argv[]){
	int res;
	MYSQL *connection;//MYSQL *
	MYSQL_RES *res_ptr;//result *
	MYSQL_ROW sqlrow;//row
	if((connection=mysql_init(NULL))==NULL)//initialize one MYSQL structure
		printf("init connection failed. %s\n",mysql_error(connection));
	if(mysql_real_connect(connection,"localhost","pgl","pgl","airp_tickets",0,NULL,0)==NULL){//using the MYSQL * to connect to the DB host
		printf("connect to mysql failed.%s\n",mysql_error(connection));
		return -1;
	}
	printf("connection success.\n");
	char sql[255];
	sprintf(sql,"select * from tickets where flight_ID=%d",3);
	res=mysql_query(connection,sql);//excute the select t_sql
	if(res){
		printf("select error:%s\n",mysql_error(connection));
		return -2;
	}else{
		res_ptr=mysql_use_result(connection);//store the result in MYSQL_RES *
		if(res_ptr){
			printf("Retrived %lu rows\n",(unsigned long)mysql_num_rows(res_ptr));
			//display the header of the data rows
			MYSQL_FIELD *field_ptr;
			while(field_ptr=mysql_fetch_field(res_ptr))
				printf("%s ",field_ptr->name);
			printf("\n");
			//deal the data
			while((sqlrow=mysql_fetch_row(res_ptr))){//deal with the data one row for each time
				printf("Fetching data...\n");
				printf("%d %s %s %s\n",atoi(sqlrow[0]),sqlrow[1],sqlrow[2],sqlrow[3]);
				if(mysql_errno(connection)){
					fprintf(stderr,"Retrive error:s\n",mysql_error(connection));
					return -3;
				}
			}
		}
		mysql_free_result(res_ptr);//free the MYSQL_RES *
	}

	mysql_close(connection);//close the connection by MYSQL *
	printf("connection closed.\n");
	
	return(0);
}

gcc -g testmysql.c -pthread -lmysqlclient -lcrypt -lm -lz -L$(MYSQLLIB) -o $(exe)mysql 2>log

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值