设为首页 加入收藏

TOP

C语言访问MySQL数据库的方法
2014-11-23 19:43:38 来源: 作者: 【 】 浏览:25
Tags:语言 访问 MySQL 数据库 方法

1、添加头文件路径(MySQL安装路径中的include路径)

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

3、编程操作数据库

代码

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

#include "stdafx.h"
#include 
#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;
}
\

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇MySQL系列:innodb引擎分析之线程.. 下一篇Mysql高级之权限检查原理

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: