C language to connect to mysql database (1)

  • Environment: vs2015
  • Prerequisite: MySQL has been installed, and successfully connected, know the user name (usually root), password

One, configuration environment

  1. Create a console application (empty project)
  2. New item, create conn.c source file
  3. Right-click the project name and click Properties
  4. Find VC++, modify: include directory and library directory respectively add include and lib folders under the mysql installation path
  5. Copy libmysql.dll in the lib (mysql installation directory) folder to the same level folder where the current conn.c file is located
  6. Change the project platform to x64

step4
step5
step6

Second, execute the code

Copy code, modify information, debug
code:

#include <stdio.h>
#include <mysql.h>
#pragma comment(lib,"libmysql.lib")

int main(void)
{
    
    
	MYSQL mysql;    //一个数据库结构体
	MYSQL_RES* res; //一个结果集结构体
	MYSQL_ROW row;  //char** 二维数组,存放一条条记录
	
	//初始化数据库
	mysql_init(&mysql);
	//设置编码方式
	mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "gbk");
	//连接数据库
	mysql_real_connect(&mysql, "localhost", "root", "***", "java", 3306, NULL, 0);
	//查询数据
	mysql_query(&mysql, "select * from person");
	//获取结果集
	res = mysql_store_result(&mysql);
	//显示数据
	printf("id\t姓名\t地址\t电话\t年龄\n");
	while (row = mysql_fetch_row(res))
	{
    
    
		// 根据数据库中的属性列 先后顺序打印字符串
		printf("%s\t", row[0]);
		printf("%s\t", row[1]);
		printf("%s\t", row[2]);
		printf("%s\t", row[3]);
		printf("%s\n", row[4]);
	}
	//释放结果集
	mysql_free_result(res);
	//关闭数据库
	mysql_close(&mysql);
	system("pause");
	return 0;
}

output
Code optimization:

#include<stdio.h>
#include<mysql.h>
#pragma comment(lib,"libmysql.lib")

int main()
{
    
    
	MYSQL mysql;
	mysql_init(&mysql);

	if (!mysql_real_connect(&mysql,
		"localhost", "root", "***", "db01", 3306, NULL, 0)) {
    
    
		printf("数据库 连接失败!");
		system("pause");
		return 0;
	}

	const char * sql = "select * from breakfast where spam=4";
	// 只进行查询,不存储数据
	if (mysql_real_query(&mysql, sql, 37)) {
    
    
		printf("查询期间出错!");
		system("pause");
		return 0;
	}

	MYSQL_RES *sr; // 结果集,记录查询结果
	MYSQL_ROW row;
	sr = mysql_store_result(&mysql);
	
	if (sr->row_count == 0) {
    
    
		printf("未查询到结果!\n");
	}

	while (row = mysql_fetch_row(sr)) {
    
    
		printf("%s\t", row[0]);
		printf("%s\t", row[1]);
		printf("%s\t", row[2]);
		printf("%s\t", row[3]);
		printf("%s\n", row[4]);
	}

	mysql_free_result(sr);
	mysql_close(&mysql);
	system("pause");
}

Next: C language to connect to mysql database (two)

Guess you like

Origin blog.csdn.net/qq_43341057/article/details/104885258