Table of Contents
一、环境配置
二、示例代码
三、mysql API接口汇总
Home Database Mysql Tutorial C++ API方式连接mysql数据库实现增删改查

C++ API方式连接mysql数据库实现增删改查

Jun 07, 2016 pm 03:47 PM
api c++ mysql accomplish database Way connect

一、环境配置 1,装好mysql,新建一个C控制台工程(从最简单的弄起,这个会了,可以往任何c工程移植),在vs2010中设置,工程--属性--VC目录--包含目录,将mysql server\include的绝对路径添加进去,例如C:\Program Files\MySQL\MySQL Server 5.6\include。

一、环境配置

1,装好mysql,新建一个C++控制台工程(从最简单的弄起,这个会了,可以往任何c++工程移植),在vs2010中设置,工程--属性--VC++目录--包含目录,将mysql server\include的绝对路径添加进去,例如C:\Program Files\MySQL\MySQL Server 5.6\include。将mysql server\lib文件夹下的libmysql.lib和libmysql.dll拷贝到工程目录下。

(也可以将include文件整个拷贝到工程目录下,然后在VC++目录里面设置相对路径)

注意:win32版的mysql的lib和dll只能用于win32编译的c++工程,同理win64的和64位的mysql对应,如果不对应会导致根本lib和dll调不了连不了数据库

如果安装的是wamp这种集成开发包,找不到include和lib也没关系,随便找个mysql免安装版根目录下的include文件夹和libmysql.lib以及libmysql.dll拷贝到工程目录,然后设置VC++目录即可。

新建一个数据库test,建立一张表user,如图

C++ API方式连接mysql数据库实现增删改查

注意有些字段需要改字符编码为utf8或者gbk,防止中文乱码。

2,为工程添加附加依赖项wsock32.lib和libmysql.lib,一种方式是工程--属性--链接器--输入--附加依赖项,另一种是在程序开头用#pragma comment(lib,"xxx.lib")

3,为程序添加头文件"mysql.h"和WinSock.h

二、示例代码

#include <stdio.h>
#include <winsock.h>  //一定要包含这个,或者winsock2.h
#include "include/mysql.h"    //引入mysql头文件(一种方式是在vc目录里面设置,一种是文件夹拷到工程目录,然后这样包含)
#include <windows.h>

//包含附加依赖项,也可以在工程--属性里面设置
#pragma comment(lib,"wsock32.lib")
#pragma comment(lib,"libmysql.lib")
MYSQL mysql; //mysql连接
MYSQL_FIELD *fd;  //字段列数组
char field[32][32];  //存字段名二维数组
MYSQL_RES *res; //这个结构代表返回行的一个查询结果集
MYSQL_ROW column; //一个行数据的类型安全(type-safe)的表示,表示数据行的列
char query[150]; //查询语句

bool ConnectDatabase();     //函数声明
void FreeConnect();
bool QueryDatabase1();  //查询1
bool QueryDatabase2();  //查询2
bool InsertData();
bool ModifyData();
bool DeleteData();
int main(int argc,char **argv)
{
	ConnectDatabase();
	QueryDatabase1();
	InsertData();
	QueryDatabase2();
	ModifyData();
	QueryDatabase2();
	DeleteData();
	QueryDatabase2();
	FreeConnect();
	system("pause");
	return 0;
}
//连接数据库
bool ConnectDatabase()
{
	//初始化mysql
	mysql_init(&mysql);  //连接mysql,数据库

	//返回false则连接失败,返回true则连接成功
	if (!(mysql_real_connect(&mysql,"localhost", "root", "", "test",0,NULL,0))) //中间分别是主机,用户名,密码,数据库名,端口号(可以写默认0或者3306等),可以先写成参数再传进去
	{
		printf( "Error connecting to database:%s\n",mysql_error(&mysql));
		return false;
	}
	else
	{
		printf("Connected...\n");
		return true;
	}
}
//释放资源
void FreeConnect()
{
	//释放资源
	mysql_free_result(res);
	mysql_close(&mysql);
}
/***************************数据库操作***********************************/
//其实所有的数据库操作都是先写个sql语句,然后用mysql_query(&mysql,query)来完成,包括创建数据库或表,增删改查
//查询数据
bool QueryDatabase1()
{
	sprintf(query, "select * from user"); //执行查询语句,这里是查询所有,user是表名,不用加引号,用strcpy也可以
	mysql_query(&mysql,"set names gbk"); //设置编码格式(SET NAMES GBK也行),否则cmd下中文乱码
	//返回0 查询成功,返回1查询失败
	if(mysql_query(&mysql, query))        //执行SQL语句
	{
		printf("Query failed (%s)\n",mysql_error(&mysql));
		return false;
	}
	else
	{
		printf("query success\n");
	}
	//获取结果集
	if (!(res=mysql_store_result(&mysql)))    //获得sql语句结束后返回的结果集
	{
		printf("Couldn't get result from %s\n", mysql_error(&mysql));
		return false;
	}

	//打印数据行数
	printf("number of dataline returned: %d\n",mysql_affected_rows(&mysql));

	//获取字段的信息
	char *str_field[32];  //定义一个字符串数组存储字段信息
	for(int i=0;iname;
	}
	for(int i=0;iname);
	int j=mysql_num_fields(res);  // 获取列数
	for(int i=0;i<j printf while for i="0;i<j;i++)" return true bool insertdata sprintf into user values if query failed false else success modifydata set email="'lilei325@163.com'" where name="'Lilei'");" deletedata from id='6");*/' char input the sql: gets><br>
运行结果:


<p><img  src="/static/imghw/default1.png" data-src="/inc/test.jsp?url=http%3A%2F%2Fimg.blog.csdn.net%2F20140718175223103%3Fwatermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMjIzNDExNQ%3D%3D%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FSouthEast&refer=http%3A%2F%2Fblog.csdn.net%2Fu012234115%2Farticle%2Fdetails%2F37934133" class="lazy" alt="C++ API方式连接mysql数据库实现增删改查" ><br>
</p>
<p><br>
</p>
<p><img  src="/static/imghw/default1.png" data-src="/inc/test.jsp?url=http%3A%2F%2Fimg.blog.csdn.net%2F20140718175229998%3Fwatermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMjIzNDExNQ%3D%3D%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FSouthEast&refer=http%3A%2F%2Fblog.csdn.net%2Fu012234115%2Farticle%2Fdetails%2F37934133" class="lazy" alt="C++ API方式连接mysql数据库实现增删改查" ></p>
<p>最好是C++输出的编码格式与数据库格式保持一致,比如都为utf8,如果插入的中文再数据库里面显示乱码,可以再代码里面加一句</p>
<p><span>mysql_set_character_set(&mysql,"utf8"); //其他编码格式类似设置<br>
</span></p>
<h1 id="span-三-mysql-API接口汇总-span"><span>三、mysql API接口汇总</span></h1>

<ul>
<li>mysql_affected_rows() 返回被最新的UPDATE, DELETE或INSERT查询影响的行数。</li>
<li>mysql_close() 关闭一个服务器连接。</li>
<li>mysql_connect() 连接一个MySQL服务器。该函数不推荐;使用mysql_real_connect()代替。</li>
<li>mysql_change_user() 改变在一个打开的连接上的用户和数据库。</li>
<li>mysql_create_db() 创建一个数据库。该函数不推荐;而使用SQL命令CREATE DATABASE。</li>
<li>mysql_data_seek() 在一个查询结果集合中搜寻一任意行。</li>
<li>mysql_debug() 用给定字符串做一个DBUG_PUSH。</li>
<li>mysql_drop_db() 抛弃一个数据库。该函数不推荐;而使用SQL命令DROP DATABASE。</li>
<li>mysql_dump_debug_info() 让服务器将调试信息写入日志文件。</li>
<li>mysql_eof() 确定是否已经读到一个结果集合的最后一行。这功能被反对; mysql_errno()或mysql_error()可以相反被使用。</li>
<li>mysql_errno() 返回最近被调用的MySQL函数的出错编号。</li>
<li>mysql_error() 返回最近被调用的MySQL函数的出错消息。</li>
<li>mysql_escape_string() 用在SQL语句中的字符串的转义特殊字符。</li>
<li>mysql_fetch_field() 返回下一个表字段的类型。</li>
<li>mysql_fetch_field_direct () 返回一个表字段的类型,给出一个字段编号。</li>
<li>mysql_fetch_fields() 返回一个所有字段结构的数组。</li>
<li>mysql_fetch_lengths() 返回当前行中所有列的长度。</li>
<li>mysql_fetch_row() 从结果集合中取得下一行。</li>
<li>mysql_field_seek() 把列光标放在一个指定的列上。</li>
<li>mysql_field_count() 返回最近查询的结果列的数量。</li>
<li>mysql_field_tell() 返回用于最后一个mysql_fetch_field()的字段光标的位置。</li>
<li>mysql_free_result() 释放一个结果集合使用的内存。</li>
<li>mysql_get_client_info() 返回客户版本信息。</li>
<li>mysql_get_host_info() 返回一个描述连接的字符串。</li>
<li>mysql_get_proto_info() 返回连接使用的协议版本。</li>
<li>mysql_get_server_info() 返回服务器版本号。</li>
<li>mysql_info() 返回关于最近执行得查询的信息。</li>
<li>mysql_init() 获得或初始化一个MYSQL结构。</li>
<li>mysql_insert_id() 返回有前一个查询为一个AUTO_INCREMENT列生成的ID。</li>
<li>mysql_kill() 杀死一个给定的线程。</li>
<li>mysql_list_dbs() 返回匹配一个简单的正则表达式的数据库名。</li>
<li>mysql_list_fields() 返回匹配一个简单的正则表达式的列名。</li>
<li>mysql_list_processes() 返回当前服务器线程的一张表。</li>
<li>mysql_list_tables() 返回匹配一个简单的正则表达式的表名。</li>
<li>mysql_num_fields() 返回一个结果集合重的列的数量。</li>
<li>mysql_num_rows() 返回一个结果集合中的行的数量。</li>
<li>mysql_options() 设置对mysql_connect()的连接选项。</li>
<li>mysql_ping() 检查对服务器的连接是否正在工作,必要时重新连接。</li>
<li>mysql_query() 执行指定为一个空结尾的字符串的SQL查询。</li>
<li>mysql_real_connect() 连接一个MySQL服务器。</li>
<li>mysql_real_query() 执行指定为带计数的字符串的SQL查询。</li>
<li>mysql_reload() 告诉服务器重装授权表。</li>
<li>mysql_row_seek() 搜索在结果集合中的行,使用从mysql_row_tell()返回的值。</li>
<li>mysql_row_tell() 返回行光标位置。</li>
<li>mysql_select_db() 连接一个数据库。</li>
<li>mysql_shutdown() 关掉数据库服务器。</li>
<li>mysql_stat() 返回作为字符串的服务器状态。</li>
<li>mysql_store_result() 检索一个完整的结果集合给客户。</li>
<li>mysql_thread_id() 返回当前线程的ID。</li>
<li>mysql_use_result() 初始化一个一行一行地结果集合的检索。</li>
</ul>


</j></windows.h></winsock.h></stdio.h>
Copy after login
Statement of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
How to use the chrono library in C? How to use the chrono library in C? Apr 28, 2025 pm 10:18 PM

Using the chrono library in C can allow you to control time and time intervals more accurately. Let's explore the charm of this library. C's chrono library is part of the standard library, which provides a modern way to deal with time and time intervals. For programmers who have suffered from time.h and ctime, chrono is undoubtedly a boon. It not only improves the readability and maintainability of the code, but also provides higher accuracy and flexibility. Let's start with the basics. The chrono library mainly includes the following key components: std::chrono::system_clock: represents the system clock, used to obtain the current time. std::chron

MySQL: The Database, phpMyAdmin: The Management Interface MySQL: The Database, phpMyAdmin: The Management Interface Apr 29, 2025 am 12:44 AM

MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

How to understand DMA operations in C? How to understand DMA operations in C? Apr 28, 2025 pm 10:09 PM

DMA in C refers to DirectMemoryAccess, a direct memory access technology, allowing hardware devices to directly transmit data to memory without CPU intervention. 1) DMA operation is highly dependent on hardware devices and drivers, and the implementation method varies from system to system. 2) Direct access to memory may bring security risks, and the correctness and security of the code must be ensured. 3) DMA can improve performance, but improper use may lead to degradation of system performance. Through practice and learning, we can master the skills of using DMA and maximize its effectiveness in scenarios such as high-speed data transmission and real-time signal processing.

How to handle high DPI display in C? How to handle high DPI display in C? Apr 28, 2025 pm 09:57 PM

Handling high DPI display in C can be achieved through the following steps: 1) Understand DPI and scaling, use the operating system API to obtain DPI information and adjust the graphics output; 2) Handle cross-platform compatibility, use cross-platform graphics libraries such as SDL or Qt; 3) Perform performance optimization, improve performance through cache, hardware acceleration, and dynamic adjustment of the details level; 4) Solve common problems, such as blurred text and interface elements are too small, and solve by correctly applying DPI scaling.

What is real-time operating system programming in C? What is real-time operating system programming in C? Apr 28, 2025 pm 10:15 PM

C performs well in real-time operating system (RTOS) programming, providing efficient execution efficiency and precise time management. 1) C Meet the needs of RTOS through direct operation of hardware resources and efficient memory management. 2) Using object-oriented features, C can design a flexible task scheduling system. 3) C supports efficient interrupt processing, but dynamic memory allocation and exception processing must be avoided to ensure real-time. 4) Template programming and inline functions help in performance optimization. 5) In practical applications, C can be used to implement an efficient logging system.

How to understand ABI compatibility in C? How to understand ABI compatibility in C? Apr 28, 2025 pm 10:12 PM

ABI compatibility in C refers to whether binary code generated by different compilers or versions can be compatible without recompilation. 1. Function calling conventions, 2. Name modification, 3. Virtual function table layout, 4. Structure and class layout are the main aspects involved.

How to optimize code How to optimize code Apr 28, 2025 pm 10:27 PM

C code optimization can be achieved through the following strategies: 1. Manually manage memory for optimization use; 2. Write code that complies with compiler optimization rules; 3. Select appropriate algorithms and data structures; 4. Use inline functions to reduce call overhead; 5. Apply template metaprogramming to optimize at compile time; 6. Avoid unnecessary copying, use moving semantics and reference parameters; 7. Use const correctly to help compiler optimization; 8. Select appropriate data structures, such as std::vector.

Steps to add and delete fields to MySQL tables Steps to add and delete fields to MySQL tables Apr 29, 2025 pm 04:15 PM

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

See all articles