search
HomeDatabaseMysql TutorialC连接MySQL数据库开发之Linux环境完整示例演示(增、删、改、查_MySQL

一、开发环境

ReadHat6.332位、mysql5.6.15、gcc4.4.6

二、编译

gcc-I/usr/include/mysql-L/usr/lib-lmysqlclient main.c -o main.out

-I:指定mysql头文件所在目录(默认去/usr/include目录下寻找所用到的头文件)

-L:指定mysql动态库文件所在目录(默认从/usr/lib目录查找)

-l:链接libmysqlclient.so动态库

-o:生成的可执行文件名

三、完整示例

////main.c//mysql数据库编程////Created by YangXin on 14-5-22.//Copyright (c) 2014年 yangxin. All rights reserved.//#include <stdio.h>#include <stdlib.h>#include <string.h>#include <mysql.h>MYSQL mysql;// 查询int query();// 修改int update();// 添加数据my_ulonglong add();// 参数化添加数据my_ulonglong addByParams();// 删除数据my_ulonglong delete();// 打印数据库服务器信息void printMySqlInfo();int main(int argc, const char * argv[]){	/*连接之前,先用mysql_init初始化MYSQL连接句柄*/	mysql_init(&mysql);		/*使用mysql_real_connect连接服务器,其参数依次为MYSQL句柄,服务器IP地址,	 登录mysql的用户名,密码,要连接的数据库等*/	if(!mysql_real_connect(&mysql, "localhost", "root", "yangxin", "test", 0, NULL, 0)) {		printf("connecting to Mysql error:%d from %s/n",mysql_errno(&mysql), mysql_error(&mysql));		return -1;	}else {		printf("Connected Mysql successful!/n");	}		printMySqlInfo();		// 设置编码	mysql_query(&mysql, "set names utf8");		// 参数化添加数据	addByParams();		// 查询	query();		// 修改	update();		// 添加	add();		// 删除	delete();		/*关闭连接*/	mysql_close(&mysql);	return 0;}// 查询int query(){	int flag, i;	const char *sql = NULL;	MYSQL_RES *res = NULL;	MYSQL_ROW row = NULL;	MYSQL_FIELD *fields = NULL;	sql = "select * from t_user" ;	flag = mysql_real_query(&mysql, sql, (unsigned int)strlen(sql));	if (flag) {		printf("query error:%d from %s/n",mysql_errno(&mysql),mysql_error(&mysql));		return -1;	}		 // 将查询结果读取到内存当中,如果数据很多的情况会比较耗内存	res = mysql_store_result(&mysql);	// res = mysql_use_result(&mysql); // 需要用到的时候,每次从服务器中读取一行		// 字段数量	unsigned int field_count = mysql_field_count(&mysql);	printf("field_cout:%d/n",field_count);		// 查询总数	my_ulonglong rows = mysql_num_rows(res);	printf("%lld/n",rows);		// 获取所有字段	fields = mysql_fetch_fields(res);	for (int i = 0; i  10";	flag = mysql_real_query(&mysql, sql, strlen(sql));	if (flag) {		printf("delete data error:%d from %s/n",mysql_errno(&mysql), mysql_error(&mysql));		return -1;	}		my_ulonglong affected_rows = mysql_affected_rows(&mysql);	printf("删除的行数:%lld/n",affected_rows);		printf("success delete %lld record data !/n",affected_rows);	return affected_rows;}void printMySqlInfo(){	const char *stat = mysql_stat(&mysql);	const char *server_info = mysql_get_server_info(&mysql);	const char *clientInfo = mysql_get_client_info();	unsigned long version =	mysql_get_client_version();	const char *hostinfo =	mysql_get_host_info(&mysql);	unsigned long serverversion = mysql_get_server_version(&mysql);	unsigned int protoinfo = mysql_get_proto_info(&mysql);		printf("stat:%s/n",stat);	printf("server_info:%s/n",server_info);	printf("clientInfo:%s/n",clientInfo);	printf("version:%ld/n",version);	printf("hostinfo:%s/n",hostinfo);	printf("serverversion:%ld/n",serverversion);	printf("protoinfo:%d/n",protoinfo);		const char *charactername = mysql_character_set_name(&mysql);	printf("client character set:%s/n",charactername);	if (!mysql_set_character_set(&mysql, "utf8"))	{		printf("New client character set: %s/n",			 mysql_character_set_name(&mysql));	}}</mysql.h></string.h></stdlib.h></stdio.h>
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

MySQL: How to Add a User RemotelyMySQL: How to Add a User RemotelyMay 12, 2025 am 12:10 AM

ToaddauserremotelytoMySQL,followthesesteps:1)ConnecttoMySQLasroot,2)Createanewuserwithremoteaccess,3)Grantnecessaryprivileges,and4)Flushprivileges.BecautiousofsecurityrisksbylimitingprivilegesandaccesstospecificIPs,ensuringstrongpasswords,andmonitori

The Ultimate Guide to MySQL String Data Types: Efficient Data StorageThe Ultimate Guide to MySQL String Data Types: Efficient Data StorageMay 12, 2025 am 12:05 AM

TostorestringsefficientlyinMySQL,choosetherightdatatypebasedonyourneeds:1)UseCHARforfixed-lengthstringslikecountrycodes.2)UseVARCHARforvariable-lengthstringslikenames.3)UseTEXTforlong-formtextcontent.4)UseBLOBforbinarydatalikeimages.Considerstorageov

MySQL BLOB vs. TEXT: Choosing the Right Data Type for Large ObjectsMySQL BLOB vs. TEXT: Choosing the Right Data Type for Large ObjectsMay 11, 2025 am 12:13 AM

When selecting MySQL's BLOB and TEXT data types, BLOB is suitable for storing binary data, and TEXT is suitable for storing text data. 1) BLOB is suitable for binary data such as pictures and audio, 2) TEXT is suitable for text data such as articles and comments. When choosing, data properties and performance optimization must be considered.

MySQL: Should I use root user for my product?MySQL: Should I use root user for my product?May 11, 2025 am 12:11 AM

No,youshouldnotusetherootuserinMySQLforyourproduct.Instead,createspecificuserswithlimitedprivilegestoenhancesecurityandperformance:1)Createanewuserwithastrongpassword,2)Grantonlynecessarypermissionstothisuser,3)Regularlyreviewandupdateuserpermissions

MySQL String Data Types Explained: Choosing the Right Type for Your DataMySQL String Data Types Explained: Choosing the Right Type for Your DataMay 11, 2025 am 12:10 AM

MySQLstringdatatypesshouldbechosenbasedondatacharacteristicsandusecases:1)UseCHARforfixed-lengthstringslikecountrycodes.2)UseVARCHARforvariable-lengthstringslikenames.3)UseBINARYorVARBINARYforbinarydatalikecryptographickeys.4)UseBLOBorTEXTforlargeuns

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.