手机版
你好,游客 登录 注册
背景:
阅读新闻

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

[日期:2014-11-17] 来源:Linux社区  作者:cjc211322 [字体:大 中 小]

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;
}

在Linux下通过C语言访问MySQL数据库的方法 http://www.linuxidc.com/Linux/2011-07/38451.htm

 

本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-11/109492.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款