温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-18 05:44:06 来源:脚本之家 阅读:301 作者:cjc雪狼 栏目:编程语言

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

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

代码

// AccessToMySQL.cpp : 定义控制台应用程序的入口点。
//
#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;
}

运行效果:

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

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI