搜索
首页数据库mysql教程Linux下C语言执行MySQL语句_MySQL

bitsCN.com

执行SQL语句的增、删、改、查的主要API函数为:

int mysql_query(MYSQL *connection, const char *query);

函数接收参数连接句柄和字符串形式的有效SQL语句(没有结束的分号,这与mysql工具不同)。如果成功,它返回0。

如果包含二进制数据的查询,要使用mysql_real_query.

检查受查询影响的行数:

my_ulonglong mysql_affected_rows(MYSQL *connection);
my_ulonglong是无符号长整形,为%lu格式
这个函数返回受之前执行update,insert或delete查询影响的行数。

例子

数据库中有一个student表

 

CREATE TABLE student (		student_no varchar(12) NOT NULL PRIMARY KEY,		student_name varchar(12) NOT NULL		); 
/

增、删、改代码:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include "mysql.h"#include "errmsg.h"#include "mysqld_error.h"MYSQL conn;void connection(const char* host, const char* user, const char* password, const char* database) {	mysql_init(&conn); // 注意取地址符&	if (mysql_real_connect(&conn, host, user, password, database, 0, NULL, 0)) {		printf("Connection success!/n");	} else {		fprintf(stderr, "Connection failed!/n");		if (mysql_errno(&conn)) {			fprintf(stderr, "Connection error %d: %s/n", mysql_errno(&conn), mysql_error(&conn));		}		exit(EXIT_FAILURE);	}}void insert() {	int res = mysql_query(&conn, "INSERT INTO student(student_no,student_name) VALUES(&#39;123465&#39;, &#39;Ann&#39;)");	if (!res) {		printf("Inserted %lu rows/n", (unsigned long)mysql_affected_rows(&conn));	} else {		fprintf(stderr, "Insert error %d: %s/n", mysql_errno(&conn), mysql_error(&conn));	}}void update() {	int res = mysql_query(&conn, "UPDATE student SET student_name=&#39;Anna&#39; WHERE student_no=&#39;123465&#39;");	if (!res) {		printf("Update %lu rows/n", (unsigned long)mysql_affected_rows(&conn));	} else {		fprintf(stderr, "Update error %d: %s/n", mysql_errno(&conn), mysql_error(&conn));	}}void delete() {	int res = mysql_query(&conn, "DELETE from student WHERE student_no=&#39;123465&#39;");	if (!res) {		printf("Delete %lu rows/n", (unsigned long)mysql_affected_rows(&conn));	} else {		fprintf(stderr, "Delete error %d: %s/n", mysql_errno(&conn), mysql_error(&conn));	}}int main (int argc, char *argv[]) {	connection("localhost", "root", "shuang", "shuangde");	delete();	mysql_close(&conn);	exit(EXIT_SUCCESS);}

返回数据的语句:select

SQL最常见的用法是提取数据而不是插入或更新数据。数据是用select语句提取的

C应用程序提取数据一般需要4个步骤:

1、执行查询

2、提取数据

3、处理数据

4、必要的清理工作

就像之前的insert和update一样,使用mysql_query来发送SQL语句,然后使用mysql_store_result或mysql_use_result来提取数据,具体使用哪个语句取决于你想如何提取数据。接着,将使用一系列mysql_fetch_row来处理数据。最后,使用mysql_free_result释放查询占用的内存资源。

一次提取所有数据:mysql_store_result

// 相关函数:// 这是在成功调用mysql_query之后使用此函数,这个函数将立刻保存在客户端中返回的所有数据。它返回一个指向结果集结构的指针,如果失败返回NULLMYSQL_RES *mysql_store_result(MYSQL *connection);// 这个函数接受由mysql_store_result返回的结果结构集,并返回结构集中的行数my_ulonglong mysql_num_rows(MYSQL_RES *result);// 这个函数从使用mysql_store_result得到的结果结构中提取一行,并把它放到一个行结构中。当数据用完或发生错误时返回NULL.MYSQL_ROW mysql_fetch_row(MYSQL_RES *resutl);// 这个函数用来在结果集中跳转,设置将会被下一个mysql_fetch_row操作返回的行。参数offset是一个行号,它必须是在0~结果总行数-1的范围内。传递// 0将会导致下一个mysql_fetch_row调用返回结果集中的第一行。void mysql_data_seek(MYSQL_RES *result, my_ulonglong offset);// 返回一个偏移值,它用来表示结果集中的当前位置。它不是行号,不能把它用于mysql_data_seekMYSQL_ROW_OFFSET mysql_row_tell(MYSQL_RES *result);// 这将在结果集中移动当前的位置,并返回之前的位置MYSQL_ROW_OFFSET mysql_row_seek(MYSQL_RES *result, MYSQL_ROW_OFFSET offset);// 完成所有对数据的操作后,必须总是调用这个来善后处理void mysql_free_result(MYSQL_RES *result);

示例代码:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include "mysql.h"#include "errmsg.h"#include "mysqld_error.h"MYSQL conn;MYSQL_RES *res_ptr;MYSQL_ROW sqlrow;void connection(const char* host, const char* user, const char* password, const char* database) {	mysql_init(&conn); // 注意取地址符&	if (mysql_real_connect(&conn, host, user, password, database, 0, NULL, 0)) {		printf("Connection success!/n");	} else {		fprintf(stderr, "Connection failed!/n");		if (mysql_errno(&conn)) {			fprintf(stderr, "Connection error %d: %s/n", mysql_errno(&conn), mysql_error(&conn));		}		exit(EXIT_FAILURE);	}}int main (int argc, char *argv[]) {	connection("localhost", "root", "shuang", "shuangde");	int res = mysql_query(&conn, "SELECT * from student");	if (res) {		fprintf(stderr, "SELECT error: %s/n", mysql_error(&conn));	} else {		res_ptr = mysql_store_result(&conn);		if (res_ptr) {			printf("Retrieved %lu rows/n", (unsigned long)mysql_num_rows(res_ptr));				while ((sqlrow = mysql_fetch_row(res_ptr))) {				printf("Fetched data.../n")	;			}			if (mysql_errno(&conn)) {				fprintf(stderr, "Retrive error: %s/n", mysql_error(&conn));			}			mysql_free_result(res_ptr);		} 	}	mysql_close(&conn);	exit(EXIT_SUCCESS);}

一次提取一行数据:mysql_use_result

使用方法和mysql_store_result完全一样,把上面代码的mysql_store_result改为mysql_use_result即可。

mysql_use_result具备资源管理方面的实质性好处,更好地平衡了网络负载,以及减少了可能非常大的数据带来的存储开销,但是不能与mysql_data_seek、mysql_row_seek、mysql_row_tell、mysql_num_rows一起使用。如果数据比较少,用mysql_store_result更好。

处理返回的数据

// 相关函数和定义:// 返回结果集中的字段(列)数目unsigned int mysql_field_count(MYSQL *connection);// 将元数据和数据提取到一个新的结构中MYSQL_FIELD *mysql_fetch_field(MYSQL *result);// 这个函数用来覆盖当前的字段编号,该编号会随着每次mysql_fetch_field调用而自动增加。如果给offset传递0,那么将跳回第1列MYSQL_FIELD_OFFSET mysql_field_seek(MYSQL *result, MYSQL_FIELD_OFFSET offset);// MYSQL_FIELD定义在sql.h中,是指向字段结构数据的指针,有关于列的信息。有成员:char *name;		// 列名,为字符串char *table;	// 列所属表名char *def;		// 如果调用mysql_list_fields,它将包含该列的默认值enum enum_field_types type;  // 列类型unsigned int length;		 // 列宽unsigned int max_length;	 // 如果使用mysql_store_result,它将包含以字节为单位的提取的最长列值的长度,如果使用mysql_use_result,将不会被设置unsigned int flags;			 // 关于列定义的标志,与得到的数据无关.常见的标志的含义有:						     //	NOT_NULL_FLAG							 // PRI_KEY_FLAG						     //	UNSIGNED_FLAG							 // AUTO_INCREMENT_FLAG							 // BINARY_FLAG等unsigned int decimals;		 // 小数点后的数字个数。// 列类型相当广泛,完整的列表见头文件mysql_com.h,常见的有://	FIELD_TYPE_DECIMAL//	FIELD_TYPE_LONG//	FIELD_TYPE_STRING//	FIELD_TYPE_VAR_STRING//一个特别有用的预定义宏: IS_NUM,当字段类型为数字时,返回true

代码示例:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include "mysql.h"#include "errmsg.h"#include "mysqld_error.h"MYSQL conn;MYSQL_RES *res_ptr;MYSQL_ROW sqlrow;void connection(const char* host, const char* user, const char* password, const char* database) {	mysql_init(&conn); // 注意取地址符&	if (mysql_real_connect(&conn, host, user, password, database, 0, NULL, 0)) {		printf("Connection success!/n");	} else {		fprintf(stderr, "Connection failed!/n");		if (mysql_errno(&conn)) {			fprintf(stderr, "Connection error %d: %s/n", mysql_errno(&conn), mysql_error(&conn));		}		exit(EXIT_FAILURE);	}}void display_row() {	unsigned int field_count = mysql_field_count(&conn);	int i = 0;	while (i < field_count) {		if (sqlrow[i]) printf("%s ", sqlrow[i]);		else printf("NULL");		i++;	}	printf("/n");}void display_header() {	MYSQL_FIELD *field_ptr;	printf("Column details:/n");	while ((field_ptr = mysql_fetch_field(res_ptr)) != NULL) {		printf("/t Name: %s/n", field_ptr->name);			printf("/t Table: %s/n", field_ptr->table);			printf("/t Type: ");		if (IS_NUM(field_ptr->type)) {			printf("Numeric field/n");			} else {			switch(field_ptr->type) {				case FIELD_TYPE_VAR_STRING:					printf("VARCHAR/n");					break;				case FIELD_TYPE_LONG:					printf("LONG");					break;				default:					printf("Type is %d, check in msyql_com.h/n", field_ptr->type);			}			}		printf("/t Max width %ld/n", field_ptr->length);		if (field_ptr->flags & AUTO_INCREMENT_FLAG)			printf("/t Auto increments/n");		printf("/n");	}}int main (int argc, char *argv[]) {	connection("localhost", "root", "shuang", "shuangde");	int res = mysql_query(&conn, "SELECT * from student");	if (res) {		fprintf(stderr, "SELECT error: %s/n", mysql_error(&conn));	} else {		res_ptr = mysql_use_result(&conn);		if (res_ptr) {			int first = 1;			while ((sqlrow = mysql_fetch_row(res_ptr))) {				if (first) {					display_header();					first = 0;					}				display_row();			}			if (mysql_errno(&conn)) {				fprintf(stderr, "Retrive error: %s/n", mysql_error(&conn));			}			mysql_free_result(res_ptr);		} 	}	mysql_close(&conn);	exit(EXIT_SUCCESS);}
bitsCN.com
声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
MySQL的许可与其他数据库系统相比如何?MySQL的许可与其他数据库系统相比如何?Apr 25, 2025 am 12:26 AM

MySQL使用的是GPL许可证。1)GPL许可证允许自由使用、修改和分发MySQL,但修改后的分发需遵循GPL。2)商业许可证可避免公开修改,适合需要保密的商业应用。

您什么时候选择InnoDB而不是Myisam,反之亦然?您什么时候选择InnoDB而不是Myisam,反之亦然?Apr 25, 2025 am 12:22 AM

选择InnoDB而不是MyISAM的情况包括:1)需要事务支持,2)高并发环境,3)需要高数据一致性;反之,选择MyISAM的情况包括:1)主要是读操作,2)不需要事务支持。InnoDB适合需要高数据一致性和事务处理的应用,如电商平台,而MyISAM适合读密集型且无需事务的应用,如博客系统。

在MySQL中解释外键的目的。在MySQL中解释外键的目的。Apr 25, 2025 am 12:17 AM

在MySQL中,外键的作用是建立表与表之间的关系,确保数据的一致性和完整性。外键通过引用完整性检查和级联操作维护数据的有效性,使用时需注意性能优化和避免常见错误。

MySQL中有哪些不同类型的索引?MySQL中有哪些不同类型的索引?Apr 25, 2025 am 12:12 AM

MySQL中有四种主要的索引类型:B-Tree索引、哈希索引、全文索引和空间索引。1.B-Tree索引适用于范围查询、排序和分组,适合在employees表的name列上创建。2.哈希索引适用于等值查询,适合在MEMORY存储引擎的hash_table表的id列上创建。3.全文索引用于文本搜索,适合在articles表的content列上创建。4.空间索引用于地理空间查询,适合在locations表的geom列上创建。

您如何在MySQL中创建索引?您如何在MySQL中创建索引?Apr 25, 2025 am 12:06 AM

toCreateAnIndexinMysql,usethecReateIndexStatement.1)forasingLecolumn,使用“ createIndexIdx_lastNameEnemployees(lastName); 2)foracompositeIndex,使用“ createIndexIndexIndexIndexIndexDx_nameOmplayees(lastName,firstName,firstName);” 3)forauniqe instex,creationexexexexex,

MySQL与Sqlite有何不同?MySQL与Sqlite有何不同?Apr 24, 2025 am 12:12 AM

MySQL和SQLite的主要区别在于设计理念和使用场景:1.MySQL适用于大型应用和企业级解决方案,支持高性能和高并发;2.SQLite适合移动应用和桌面软件,轻量级且易于嵌入。

MySQL中的索引是什么?它们如何提高性能?MySQL中的索引是什么?它们如何提高性能?Apr 24, 2025 am 12:09 AM

MySQL中的索引是数据库表中一列或多列的有序结构,用于加速数据检索。1)索引通过减少扫描数据量提升查询速度。2)B-Tree索引利用平衡树结构,适合范围查询和排序。3)创建索引使用CREATEINDEX语句,如CREATEINDEXidx_customer_idONorders(customer_id)。4)复合索引可优化多列查询,如CREATEINDEXidx_customer_orderONorders(customer_id,order_date)。5)使用EXPLAIN分析查询计划,避

说明如何使用MySQL中的交易来确保数据一致性。说明如何使用MySQL中的交易来确保数据一致性。Apr 24, 2025 am 12:09 AM

在MySQL中使用事务可以确保数据一致性。1)通过STARTTRANSACTION开始事务,执行SQL操作后用COMMIT提交或ROLLBACK回滚。2)使用SAVEPOINT可以设置保存点,允许部分回滚。3)性能优化建议包括缩短事务时间、避免大规模查询和合理使用隔离级别。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具