栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言实现访问及查询MySQL数据库的方法

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言实现访问及查询MySQL数据库的方法

本文实例讲述了C语言实现访问及查询MySQL数据库的方法。分享给大家供大家参考,具体如下:

1、添加头文件路径(MySQL安装路径中的include路径)
2、添加库文件(直接从MySQL安装路径中copy libmysql.lib即可)
3、编程操作数据库

代码

// AccessToMySQL.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include 
#include 
#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("%st%st%sn",row[0],row[1],row[2]);
    }
  }
  //release the resource
  mysql_free_result(result);
  mysql_close(&mysql);
  system("pause");
  return 0;
}

运行效果:

希望本文所述对大家C语言程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/63100.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号