C語言實(shí)現(xiàn)訪問及查詢MySQL數(shù)據(jù)庫的方法
更新時(shí)間:2018年01月04日 11:30:42 作者:cjc雪狼
這篇文章主要介紹了C語言實(shí)現(xiàn)訪問及查詢MySQL數(shù)據(jù)庫的方法,涉及C語言基于libmysql.lib實(shí)現(xiàn)訪問MySQL數(shù)據(jù)庫的相關(guān)操作技巧,需要的朋友可以參考下
本文實(shí)例講述了C語言實(shí)現(xiàn)訪問及查詢MySQL數(shù)據(jù)庫的方法。分享給大家供大家參考,具體如下:
1、添加頭文件路徑(MySQL安裝路徑中的include路徑)
2、添加庫文件(直接從MySQL安裝路徑中copy libmysql.lib即可)
3、編程操作數(shù)據(jù)庫
代碼
// AccessToMySQL.cpp : 定義控制臺應(yīng)用程序的入口點(diǎn)。
//
#include "stdafx.h"
#include <Windows.h>
#include <mysql.h>
#pragma comment(lib,"libmysql.lib")
MYSQL mysql;
MYSQL_RES* result;
MYSQL_ROW row;
int main(void)
{
//init the mysql parameter
mysql_init(&mysql);
//connect the database
if(!mysql_real_connect(&mysql,"127.0.0.1","root","111","mytest",3306,NULL,0))
{
printf(mysql_error(&mysql));
printf("\nCannot access to the database!!!\n");
system("pause");
exit(-1);
}
//construct the query SQL statements
char* sql="select * from student where name='";
char dest[100]={""};
strcat(dest,sql);
printf("Please enter the student name:");
char name[10]={""};
gets(name);
strcat(dest,name);
strcat(dest,"'");
//excute the SQL statements
if(mysql_query(&mysql,dest))
{
printf("Cannot access the database with excuting \"%s\".",dest);
system("pause");
exit(-1);
}
//deal with the result
result=mysql_store_result(&mysql);
if(mysql_num_rows(result))
{
while((row=mysql_fetch_row(result)))
{
printf("%s\t%s\t%s\n",row[0],row[1],row[2]);
}
}
//release the resource
mysql_free_result(result);
mysql_close(&mysql);
system("pause");
return 0;
}
運(yùn)行效果:

希望本文所述對大家C語言程序設(shè)計(jì)有所幫助。
相關(guān)文章
簡單對比C語言中的fputs()函數(shù)和fputc()函數(shù)
這篇文章主要介紹了簡單對比C語言中的fputs()函數(shù)和fputc()函數(shù),注意其之間的區(qū)別,需要的朋友可以參考下2015-08-08

