C language to connect to mysql database (two)

The previous article "C Language Connecting MySQL Database (1)" focused on the connection configuration under the vs environment.
This article focuses on the operation of the database

  1. select query database situation
#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=0";
	// 只进行查询,不修改数据库
	if (mysql_real_query(&mysql, sql, 37)) {
    
    
		printf("sql语句执行期间出错!");
		system("pause");
		return 0;
	}

	MYSQL_RES *sr; // 结果集,记录查询结果

	sr = mysql_store_result(&mysql);
	
	if (sr->row_count == 0) {
    
    
		printf("sql 语句无返回结果\n");
	}
	else {
    
    
		MYSQL_ROW row;
		// 打印所有属性列,不考虑索引
		while (row = mysql_fetch_row(sr)) {
    
    
			while (strcmp("", *(row)))
			{
    
    
				printf("%s\t", *(row++));
			}
			printf("\n");
		}
	}

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

  1. Non-query database situation (insert, delete, update, etc.)
#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("数据库连接失败!\n");
		system("pause");
		return 0;
	}

	const char * sql = "insert into breakfast values('dududu',1,2,3,88.88)";

	if (mysql_real_query(&mysql, sql, strlen(sql))) {
    
    
		printf("sql 语句执行出错\n");
		system("pause");
		return 0;
	}
	// mysql_real_query函数判断sql语句是否执行成功
	// 对于非select 语句,没有结果集,调用mysql_store_result函数没意义


	//MYSQL_RES *sr = mysql_store_result(&mysql);

	system("pause");
}

Guess you like

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