C language connects to MySQL and executes SQL statements (hello world)

1. Create a new console project

Reference [VS2022 and VS2010 C language console outputs Hello World] VS2022 and VS2010 C language console outputs Hello World_Where is the source file of vs2022_Xijin's no1 blog-CSDN blog

2.Install MySQL _

Refer to [ MySQL 8.0.34 Installation Tutorial ] MySQL 8.0.34 Installation Tutorial_Xi Jin’s no1 blog-CSDN blog

3. Copy the MySQL library file to the project file

You can see the include folder and lib folder under the MySQL installation folder. Copy the include folder and lib folder and all the files in them to the project folder (demo.cpp is in the same folder), and copy the libmysql.dll file under the lib folder to the project folder (demo .cpp in the same folder).

Among them, the include folder stores header files (method declarations), and the lib folder stores dynamic and static libraries (method implementations, packaged into libraries).

4. Create a new "stdbool.h" file with the following content, copy the file to the project folder

The purpose of this step is to solve the vs compilation error: fatalerrorc1083: Unable to open include file: "stdbool.h": nosuchfileordirectory (code snippet).

The contents of the "stdbool.h" file are as follows:

/*
 * ISO C Standard:  7.16  Boolean type and values  <stdbool.h>
 */
 
#ifndef __STDBOOL_H__
#define __STDBOOL_H__
#define bool	int
#define true	1
#define false	0
#endif
/* __STDBOOL_H__ */

The "stdbool.h" file is placed in the include folder in the project folder.

5.Configure the calling library

Note that for all the following configurations, you need to first select the platform win32 or x64 corresponding to the MySQL library, otherwise an error will occur.

as follows:

error LNK2019: Unresolved external symbol _mysql_real_connect@32, which is referenced in function _main

error LNK2019: Unresolved external symbol _mysql_query@8, which is referenced in function _main

error LNK2019: Unresolved external symbol _mysql_init@4, which is referenced in function _main

error LNK2019: Unresolvable external symbol _mysql_close@4. When this symbol is referenced in function _main and other errors occur, it is because the number of bits in the vs project does not match the number of bits in the MySQL library.

You can change the project properties. The project properties need to be changed in two places (note that the library configuration under the corresponding platform must be modified simultaneously):

(1) Project Properties-->[Configuration Properties]-->[VC++ Directory]-->[Inclusion Directory]: Select the directory where the header file in the mysql library is located

Project folder include folder

or

C:\Program Files\MySQL\MySQL Server 8.0\include

(2) Project properties --> [Configuration Properties] --> [VC++ Directory] --> [Library Directory]: Select the directory where the static library in the mysql library is located

Project folder lib folder

or

C:\Program Files\MySQL\MySQL Server 8.0\lib

(3) Project properties --> [Configuration Properties] --> [Linker] --> [Input] --> [Additional Dependencies]

Add libmysql.lib.

6. Sample code 1 - Verify whether the MySQL library configuration and call are successful

Overwrite the content in demo.cpp with the following code.

#include <stdio.h>
#include <winsock.h>
#include <mysql.h>
int main()
{

	MYSQL*mysql=mysql_init(0);
	system("pause");
	return 0;
}

The above code is compiled successfully, indicating that the configuration is successful. If it runs successfully, it means that the MySQL library is called successfully.

 

7. Sample code 2- Get MySQL client version

Overwrite the content in demo.cpp with the following code.

#include <stdio.h>
#include <winsock.h>
#include <mysql.h>
int main()
{

	//获取客户端的版本信息
    printf("mysql client version:%s\n", mysql_get_client_info());
	system("pause");
	return 0;
}

8. Sample code 3- Query the data in the orderitems table and print it out

This example requires many prerequisites: 1. A database; 2. There are tables in the database; 3. There are data in the tables; 4. Users with read and write permissions to the database, etc.

#include <stdio.h>
#include <winsock.h>
#include <mysql.h>

const char host[] = "127.0.0.1";	// MySQL所在机器的ip
const int port = 0;					// MySQL所在机器的端口
const char db[] = "test";			// 数据库名
const char user[] = "root";			// 用户名
const char passwd[] = "test123";	// 用户密码

int main()
{
	//1、获取MySQL实例(相当于创建了一个MySQL句柄)
	MYSQL* ms = mysql_init(nullptr);

	//2、连接数据库
	if(mysql_real_connect(ms, host, user, passwd, db, port, nullptr, 0) == nullptr) {
		printf("数据库连接失败!\n");
		return 1;
	}
	printf("数据库连接成功!\n");
	mysql_set_character_set(ms, "utf8"); //设置编码格式为utf8

	//3、查询数据库表中的记录

	//a、执行查询语句
	char sql[] = "select * from orderitems;";
	if(mysql_query(ms, sql) != 0) {
		printf("查询数据失败!\n");
		return 2;
	}
	printf("查询数据成功!\n");
	//b、获取查询结果
	MYSQL_RES* res = mysql_store_result(ms);
	int rows = mysql_num_rows(res); //行数
	int cols = mysql_num_fields(res); //列数
	//获取每列的属性并打印列名
	MYSQL_FIELD* fields = mysql_fetch_fields(res);
	for(int i = 0;i < cols;i++) printf("%s\t", fields[i].name);
	printf("\n");

	for(int i = 0;i < rows;i++) {
		//获取一行数据并进行打印
		MYSQL_ROW row = mysql_fetch_row(res);
		for(int j = 0;j < cols;j++) {
			printf("%s\t", row[j]);
		}
		printf("\n");
	}
	
    mysql_free_result(res); // 释放内存空间

	//4、关闭数据库
	mysql_close(ms);
	printf("数据库关闭成功!\n");
	return 0;
}

Written at the end : This article only shows the basic content of using the MySQL library, and does not introduce too much content about MySQL's C language interface. Readers are asked to expand and learn on their own.

Guess you like

Origin blog.csdn.net/xijinno1/article/details/133238180