C/C++连接MySQL数据库执行查询
1. 简介:
使用C/C++连接MySQL数据库执行增删改查操作,基本就是围绕以下两个文件展开:
- mysql.h(此头文件一般在MySQL的include文件夹内,如 D:\MySQL\mysql-5.7.23-winx64\include)
- MySQL官方 C API
C/C++连接数据库执行查询操作时需要将sql查询语句嵌入到mysql_query语句中,具体见API中的mysql_query()函数
2. 数据库安装
本文代码是以MySQL官方实例数据库employees为对象进行的查询,如果想直接运行下述代码,需要安装employees数据库,当然也可以使用下述代码对其他数据库进行查询,只需要修改代码中的部分sql语句。下面介绍一下employees数据库的安装:
employees下载:(一下两种方法都可以,任选其一,两方法得到的文件相同test_db-master.zip)
- 百度云【提取码 mwrz 】
employees安装:
3. 完整代码
/*
C/C++连接MySQL数据库时,需要包含一个*.h的mysql头文件和一个mysql的lib文件
1、初始化;2、连接数据库;3、执行sql查询语句;4、获取查询值;5、关闭
*/
#include <stdio.h>
#include <WinSock.h>
#include <mysql.h>
#include <Windows.h>
#pragma comment(lib,"wsock32.lib")
#pragma comment(lib,"libmysql.lib") MYSQL mysql;
MYSQL_FIELD *fd; //字段列数组
char field[][]; //存字段名二维数组
MYSQL_RES *res; //行的一个查询结果集
MYSQL_ROW column; //数据行的列
char query[]; //查询语句 //函数声明
bool ConnectDatabase();
void FreeConnect();
bool QueryDatabase();
bool InsertData();
bool ModifyData();
bool DeleteData(); int main(int argc, char **argv){
ConnectDatabase();
QueryDatabase();
InsertData();
QueryDatabase();
ModifyData();
QueryDatabase();
//DeleteData();
//QueryDatabase();
FreeConnect();
system("pause");
return ;
} //连接数据库
bool ConnectDatabase(){
//Gets or initializes a MYSQL structure
mysql_init(&mysql); // Connects to a MySQL server
const char host[] = "localhost";
const char user[] = "root";
const char passwd[] = "root";
const char db[] = "employees";
unsigned int port = ;
const char *unix_socket = NULL;
unsigned long client_flag = ; /*A MYSQL* connection handler if the connection was successful,
NULL if the connection was unsuccessful. For a successful connection,
the return value is the same as the value of the first parameter.*/
if (mysql_real_connect(&mysql, host, user, passwd, db, port, unix_socket, client_flag)){
printf("The connection was successful.\n");
return true;
}
else{
/*const char *mysql_error(MYSQL *mysql)
Returns the error message for the most recently invoked MySQL function
A null-terminated character string that describes the error.
An empty string if no error occurred.*/
printf("Error connecting to database:%s\n", mysql_error(&mysql));
return false;
}
} //释放资源
/*void mysql_free_result(MYSQL_RES *result)
Frees the memory allocated for a result set by mysql_store_result(),
mysql_use_result(), mysql_list_dbs(), and so forth.When you are done
with a result set, you must free the memory it uses by calling mysql_free_result().
Do not attempt to access a result set after freeing it.*/ /*void mysql_close(MYSQL *mysql)
Closes a previously opened connection.mysql_close() also deallocates
the connection handler pointed to by mysql if the handler was allocated
automatically by mysql_init() or mysql_connect().*/
void FreeConnect(){
mysql_free_result(res);
mysql_close(&mysql);
} //查询数据
bool QueryDatabase(){
//将数据格式化输出到字符串
sprintf_s(query, "select * from departments");
//设置编码格式
mysql_query(&mysql, "set names gbk"); /*int mysql_query(MYSQL *mysql, const char *stmt_str)
Executes an SQL query specified as a null-terminated string
Executes the SQL statement pointed to by the null-terminated string stmt_str.
Normally, the string must consist of a single SQL statement without
a terminating semicolon (;). If multiple-statement execution has been enabled,
the string can contain several statements separated by semicolons.
Return Values:Zero for success. Nonzero if an error occurred.*/
if (mysql_query(&mysql, query)){
printf("Query failed (%s)\n", mysql_error(&mysql));
return false;
}
else{
printf("query success\n");
} /*MYSQL_RES *mysql_store_result(MYSQL *mysql)
Retrieves a complete result set to the client
mysql_store_result() reads the entire result of a query to the client,
allocates a MYSQL_RES structure, and places the result into this structure.
mysql_store_result() returns a null pointer if the statement did not return
a result set(for example, if it was an INSERT statement). mysql_store_result()
also returns a null pointer if reading of the result set failed.
You can check whether an error occurred by checking whether mysql_error()
returns a nonempty string. Return Values:A MYSQL_RES result structure with
the results.NULL(0) if an error occurred.*/
res = mysql_store_result(&mysql);
if (!res){
printf("Couldn't get result from %s\n", mysql_error(&mysql));
return false;
} /*my_ulonglong mysql_affected_rows(MYSQL *mysql)
It returns the number of rows changed, deleted,
or inserted by the last statement if it was an UPDATE, DELETE, or INSERT.
For SELECT statements, returns the number of rows in the result set.*/
printf("number of dataline returned: %d\n", mysql_affected_rows(&mysql)); /*MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result)
Returns the definition of one column of a result set as a MYSQL_FIELD structure.
Call this function repeatedly to retrieve information about all columns in the result set.*/ // 获取列数
int j = mysql_num_fields(res); //存储字段信息
char *str_field[]; //获取字段名
for (int i = ; i < j; i++){
str_field[i] = mysql_fetch_field(res)->name;
} //打印字段
for (int i = ; i < j; i++)
printf("%10s\t", str_field[i]);
printf("\n"); //打印查询结果
//MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)
//Fetches the next row from the result set
while (column = mysql_fetch_row(res)){
printf("%10s\t%10s\n", column[], column[]);
}
return true;
} //插入数据
bool InsertData(){
sprintf_s(query, "insert into departments values ('xxxx', 'xxxxx');");
if (mysql_query(&mysql, query)) {
printf("Query failed (%s)\n", mysql_error(&mysql));
return false;
}
else{
printf("Insert success\n");
return true;
}
} //修改数据
bool ModifyData(){
sprintf_s(query, "update departments set dept_name='yyyyy' where dept_no='xxxx'");
if (mysql_query(&mysql, query)) {
printf("Query failed (%s)\n", mysql_error(&mysql));
return false;
}
else{
printf("Insert success\n");
return true;
}
} //删除数据
bool DeleteData()
{
sprintf_s(query, "delete from departments where dept_no='xxxx';");
if (mysql_query(&mysql, query)) {
printf("Query failed (%s)\n", mysql_error(&mysql));
return false;
}
else{
printf("Insert success\n");
return true;
}
}
C/C++连接MySQL数据库执行查询的更多相关文章
- MFC连接Mysql数据库执行查询和插入
配置环境: include:mysql.h文件 lib:libmysql.lib文件 dll::libmysql.dll文件 连接代码: MYSQL m_sqlCon; MYSQL_RES *m_re ...
- nodejs进阶(6)—连接MySQL数据库
1. 建库连库 连接MySQL数据库需要安装支持 npm install mysql 我们需要提前安装按mysql sever端 建一个数据库mydb1 mysql> CREATE DATABA ...
- Java使用JDBC连接MySQL数据库
1.引用 JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写 ...
- MATLAB连接MySQL数据库
今天开始看<MATLAB数据分析与挖掘实战>,学习了下用MATLAB连接MySQL数据库,环境win7,32bit,MySQL5.7.12,MATLAB2013B 首先,从这里下载驱动的压 ...
- JDBC连接MySQL数据库及示例
JDBC是Sun公司制定的一个可以用Java语言连接数据库的技术. 一.JDBC基础知识 JDBC(Java Data Base Connectivity,java数据库连接)是一 ...
- Java连接MySQL数据库及简单操作代码
1.Java连接MySQL数据库 Java连接MySql需要下载JDBC驱动MySQL-connector-java-5.0.5.zip(举例,现有新版本).然后将其解压缩到任一目录.我是解压到D盘, ...
- 一个非常标准的连接Mysql数据库的示例代码
一.About Mysql 1.Mysql 优点 体积小.速度快.开放源码.免费 一般中小型网站的开发都选择 MySQL ,最流行的关系型数据库 LAMP / LNMP Linux作为操作系统 Apa ...
- java用JDBC连接MySQL数据库的详细知识点
想实现java用JDBC连接MySQL数据库.需要有几个准备工作: 1.下载Connector/J的库文件,下载Connector/J的官网地址:http://www.mysql.com/downlo ...
- Eclipse中利用JSP把mysql-connector-java-8.0.13.jar放到WebContent\WEB-INF\lib中连接MySQL数据库时Connection conn = DriverManager.getConnection(url,username,password)报错的解决办法
开发环境: 1.系统:windows 7/8/10均可 2.jdk:1.8.0_144 3.服务器:apache-tomcat-9.0.8 4.IDE:eclipse+jsp 0.网页代码如下: &l ...
随机推荐
- 拓扑排序+DFS(POJ1270)
[日后练手](非解题) 拓扑排序+DFS(POJ1270) #include<stdio.h> #include<iostream> #include<cstdio> ...
- Linux下tcp服务器创建的步骤
创建一个socket,使用函数socket() socket(套接字)实质上提供了进程通信的端点,进程通信之前,双方首先必须建立各自的一个端点,否则没有办法通信.通过socket将IP地址和端口绑定之 ...
- hdu1325 Is It A Tree? 基础并查集
#include <stdio.h> #include <string.h> ], g[]; int find(int x) //并查集的查找,找到共同的父亲 { if (f[ ...
- bzoj 4860 [BeiJing2017]树的难题
题面 https://www.lydsy.com/JudgeOnline/problem.php?id=4860 题解 点分治 设当前重心为v 假设已经把所有边按照出发点第一关键字, 颜色第二关键字排 ...
- 洛谷 P2147 [SDOI2008]洞穴勘测
以下这个做法应该是叫线段树分治... 根据修改操作预处理出每条边存在的时间区间[l,r](以操作序号为时间),然后把所有形式化后的修改挂到线段树节点上. 处理完修改后,dfs一遍线段树,进入某个节点时 ...
- 132 Palindrome Partitioning II 分割回文串 II
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串.返回 s 符合要求的的最少分割次数.例如,给出 s = "aab",返回 1 因为进行一次分割可以将字符串 s 分 ...
- D. The Door Problem 带权并查集
http://codeforces.com/contest/776/problem/D 注意到每扇门都有两个东西和它连接着,那么,如果第i扇门的状态是1,也就是已经打开了,那么连接它的两个按钮的状态应 ...
- 【前端】jq弹出一个透明小提示窗,然后逐渐消失
function show_main(content) { var showWindow = '<div id="show_main" style="borde ...
- C# 图片打印杂谈
日常开头水一下,看了下上次博客,一年零八天了,啧啧,奢侈. 最近这个工作挺满意的,是我想要的发展方向,后续要做机器学习,现在得先把公司之前堆积的问题解决了. 谈人生到此结束,还是说正题吧.(感觉这标题 ...
- 移动端超级好用的reset.css(只做参考哦具体以你们实际项目需求为准)
html { color: #333; /*规定主色调,依据业务场景(非必须)*/ background: #F6F6F6; /*规定主背景,依据业务场景(非必须)*/ overflow-y: aut ...