搜索
查看: 1127|回复: 0

【MySql】C语言访问MySQL数据库的方法

[复制链接]

153

主题

3

回帖

479

积分

中级会员

积分
479
发表于 2014-11-18 15:13:26 | 显示全部楼层 |阅读模式
1、添加头文件路径(MySQL安装路径中的include路径)

2、添加库文件(直接从MySQL安装路径中copy libmysql.lib即可)

3、编程操作数据库

代码
  1. // AccessToMySQL.cpp : 定义控制台应用程序的入口点。
  2. //

  3. #include "stdafx.h"
  4. #include <Windows.h>
  5. #include <mysql.h>
  6. #pragma comment(lib,"libmysql.lib")

  7. MYSQL mysql;
  8. MYSQL_RES* result;
  9. MYSQL_ROW row;

  10. int main(void)
  11. {
  12.     //init the mysql parameter
  13.     mysql_init(&mysql);
  14.     //connect the database
  15.     if(!mysql_real_connect(&mysql,"127.0.0.1","root","111","mytest",3306,NULL,0))
  16.     {
  17.         printf(mysql_error(&mysql));
  18.         printf("\nCannot access to the database!!!\n");
  19.         system("pause");
  20.         exit(-1);
  21.     }
  22.      
  23.     //construct the query SQL statements
  24.     char* sql="select * from student where name='";
  25.     char dest[100]={""};
  26.     strcat(dest,sql);
  27.     printf("Please enter the student name:");
  28.     char name[10]={""};
  29.     gets(name);
  30.     strcat(dest,name);
  31.     strcat(dest,"'");

  32.     //excute the SQL statements
  33.     if(mysql_query(&mysql,dest))
  34.     {
  35.         printf("Cannot access the database with excuting "%s".",dest);
  36.         system("pause");
  37.         exit(-1);
  38.     }

  39.     //deal with the result
  40.     result=mysql_store_result(&mysql);
  41.     if(mysql_num_rows(result))
  42.     {
  43.         while((row=mysql_fetch_row(result)))
  44.         {
  45.             printf("%s\t%s\t%s\n",row[0],row[1],row[2]);
  46.         }
  47.     }
  48.     //release the resource
  49.     mysql_free_result(result);
  50.     mysql_close(&mysql);
  51.      
  52.     system("pause");
  53.     return 0;
  54. }
复制代码



您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

 
 
大数据行业交流
大数据行业交流
大数据求职招聘
大数据求职招聘
站长电话:
15010106923
微信联系:
hb-0310
站长邮箱:
ab12-120@163.com
大数据中国微信

QQ   

版权所有: Discuz! © 2001-2013 大数据.

GMT+8, 2024-5-2 20:15 , Processed in 0.070713 second(s), 24 queries .

快速回复 返回顶部 返回列表