C/C++连接MySQL数据库执行查询(对employees进行查询)

C/C++连接MySQL数据库执行查询(以employees数据库为对象进行查询)

  1 /*
  2 C/C++连接MySQL数据库时,需要包含一个*.h的mysql头文件和一个mysql的lib文件
  3 1、初始化;
  4 2、连接数据库;
  5 3、执行sql查询语句;
  6 4、获取查询值;
  7 5、关闭
  8 */
  9 #include <stdio.h>
 10 #include <WinSock.h>
 11 #include <mysql.h>
 12 #include <Windows.h>
 13 #pragma comment(lib,"wsock32.lib")
 14 #pragma comment(lib,"libmysql.lib")
 15
 16 MYSQL mysql;
 17 MYSQL_FIELD *fd;    //字段列数组
 18 char field[32][32]; //存字段名二维数组
 19 MYSQL_RES *res;     //行的一个查询结果集
 20 MYSQL_ROW column;   //数据行的列
 21 char query[150];    //查询语句
 22
 23 //函数声明
 24 bool ConnectDatabase();
 25 void FreeConnect();
 26 bool QueryDatabase();
 27 bool InsertData();
 28 bool ModifyData();
 29 bool DeleteData();
 30
 31 int main(int argc, char **argv){
 32     ConnectDatabase();
 33     QueryDatabase();
 34     InsertData();
 35     QueryDatabase();
 36     ModifyData();
 37     QueryDatabase();
 38     //DeleteData();
 39     //QueryDatabase();
 40     FreeConnect();
 41     system("pause");
 42     return 0;
 43 }
 44
 45 //连接数据库
 46 bool ConnectDatabase(){
 47     //Gets or initializes a MYSQL structure
 48     mysql_init(&mysql);
 49
 50     // Connects to a MySQL server
 51     const char host[] = "localhost";
 52     const char user[] = "root";
 53     const char passwd[] = "root";
 54     const char db[] = "employees";
 55     unsigned int port = 3306;
 56     const char *unix_socket = NULL;
 57     unsigned long client_flag = 0;
 58
 59     //A MYSQL* connection handler if the connection was successful,
 60     //NULL if the connection was unsuccessful. For a successful connection,
 61     //the return value is the same as the value of the first parameter.
 62     if (mysql_real_connect(&mysql, host, user, passwd, db, port, unix_socket, client_flag)){
 63         printf("The connection was successful.\n");
 64         return true;
 65     }
 66     else{
 67         //const char *mysql_error(MYSQL *mysql)
 68         //Returns the error message for the most recently invoked MySQL function
 69         //A null-terminated character string that describes the error.
 70         //An empty string if no error occurred.
 71         printf("Error connecting to database:%s\n", mysql_error(&mysql));
 72         return false;
 73     }
 74 }
 75
 76 //释放资源
 77 //void mysql_free_result(MYSQL_RES *result)
 78 //Frees the memory allocated for a result set by mysql_store_result(),
 79 //mysql_use_result(), mysql_list_dbs(), and so forth.
 80 //When you are done with a result set, you must free the memory it
 81 //uses by calling mysql_free_result().
 82 //Do not attempt to access a result set after freeing it.
 83
 84 //void mysql_close(MYSQL *mysql)
 85 //Closes a previously opened connection.mysql_close() also deallocates
 86 //the connection handler pointed to by mysql if the handler was allocated automatically
 87 //by mysql_init() or mysql_connect().
 88 void FreeConnect(){
 89     mysql_free_result(res);
 90     mysql_close(&mysql);
 91 }
 92
 93 //查询数据
 94 bool QueryDatabase(){
 95     //将数据格式化输出到字符串
 96     sprintf_s(query, "select * from departments");
 97     //设置编码格式
 98     mysql_query(&mysql, "set names gbk");
 99
100     //int mysql_query(MYSQL *mysql, const char *stmt_str)
101     //Executes an SQL query specified as a null-terminated string
102     //Executes the SQL statement pointed to by the null-terminated string stmt_str.
103     //Normally, the string must consist of a single SQL statement without a terminating semicolon (;) or \g.
104     //If multiple-statement execution has been enabled, the string can contain several statements separated by semicolons.
105     //Return Values:Zero for success.Nonzero if an error occurred.
106     if (mysql_query(&mysql, query)){
107         printf("Query failed (%s)\n", mysql_error(&mysql));
108         return false;
109     }
110     else{
111         printf("query success\n");
112     }
113
114     //MYSQL_RES *mysql_store_result(MYSQL *mysql)
115     //Retrieves a complete result set to the client
116     //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.
117     //mysql_store_result() returns a null pointer if the statement did not return a result set(for example, if it was an INSERT statement).
118     //mysql_store_result() also returns a null pointer if reading of the result set failed.
119     //You can check whether an error occurred by checking whether mysql_error() returns a nonempty string.
120     //Return Values: A MYSQL_RES result structure with the results.NULL(0) if an error occurred.
121     res = mysql_store_result(&mysql);
122     if (!res){
123         printf("Couldn‘t get result from %s\n", mysql_error(&mysql));
124         return false;
125     }
126
127     //my_ulonglong mysql_affected_rows(MYSQL *mysql)
128     //It returns the number of rows changed, deleted,
129     //or inserted by the last statement if it was an UPDATE, DELETE, or INSERT.
130     //For SELECT statements, returns the number of rows in the result set.
131     printf("number of dataline returned: %d\n", mysql_affected_rows(&mysql));
132
133     //获取字段的信息
134     //MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result)
135     //Returns the definition of one column of a result set as a MYSQL_FIELD structure.
136     //Call this function repeatedly to retrieve information about all columns in the result set.
137
138     // 获取列数
139     int j = mysql_num_fields(res);
140
141     char *str_field[32];  //存储字段信息
142
143     //获取字段名
144     for (int i = 0; i < j; i++){
145         str_field[i] = mysql_fetch_field(res)->name;
146     }
147
148     //打印字段
149     for (int i = 0; i < j; i++)
150         printf("%10s\t", str_field[i]);
151     printf("\n");
152
153     //打印查询结果
154     //MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)
155     //Fetches the next row from the result set
156     while (column = mysql_fetch_row(res)){
157         printf("%10s\t%10s\n", column[0], column[1]);
158     }
159     return true;
160 }
161
162 //插入数据
163 bool InsertData()
164 {
165     sprintf_s(query, "insert into departments values (‘dddd‘, ‘xxxxx‘);");
166     if (mysql_query(&mysql, query)) {
167         printf("Query failed (%s)\n", mysql_error(&mysql));
168         return false;
169     }
170     else{
171         printf("Insert success\n");
172         return true;
173     }
174 }
175
176 //修改数据
177 bool ModifyData(){
178     sprintf_s(query, "update departments set dept_name=‘yyyyy‘ where dept_no=‘dddd‘");
179     if (mysql_query(&mysql, query)) {
180         printf("Query failed (%s)\n", mysql_error(&mysql));
181         return false;
182     }
183     else{
184         printf("Insert success\n");
185         return true;
186     }
187 }
188
189 //删除数据
190 bool DeleteData()
191 {
192     sprintf_s(query, "delete from departments where dept_no=‘dddd‘;");
193     //char query[100];
194     //printf("please input the sql:\n");
195     //gets_s(query);  //手动输入sql语句
196     if (mysql_query(&mysql, query)) {
197         printf("Query failed (%s)\n", mysql_error(&mysql));
198         return false;
199     }
200     else{
201         printf("Insert success\n");
202         return true;
203     }
204 }

原文地址:https://www.cnblogs.com/iwangzhengchao/p/10056075.html

时间: 2024-10-08 13:05:29

C/C++连接MySQL数据库执行查询(对employees进行查询)的相关文章

python连接mysql数据库带where条件的查询操作

#encoding=utf-8import MySQLdbclass Sjb_data(): def __init__(self): self.url = url def mysql(self,sql): db = MySQLdb.connect(host='IP地址',port = 3306,user=r'用户名',passwd='密码',db ='数据库名',charset= 'utf8') cur = db.cursor() cur.execute(sql) #执行sql #data =

jdbc 连接mysql数据库

jdbc驱动到官网下载,放在jdk的相关目录下面,或者jar文件加入到工程下面 package test_mysql; import java.sql.*; import java.util.Set; public class testjdbc { public static Connection getConnection() throws ClassNotFoundException, SQLException{ String URL="jdbc:mysql://localhost:3306

连接Mysql数据库

JDBC连接数据库 创建一个以JDBC连接数据库的程序,包含7个步骤: 1.加载JDBC驱动程序: 在连接数据库之前,首先要加载想要连接的数据库的驱动到JVM(Java虚拟机), 这通过java.lang.Class类的静态方法forName(String className)实现. 例如: try{ //加载MySql的驱动类 Class.forName("com.mysql.jdbc.Driver"); } catch(ClassNotFoundException e) { Sys

分页查询信息(使用jdbc连接mysql数据库实现分页查询任务)

         分页查询信息       使用jdbc连接mysql数据库实现分页查询任务 通过mysql数据库提供的分页机制,实现商品信息的分页查询功能,将查询到的信息显示到jsp页面上. 本项目时一个简单的运用eclipse+jdbc+mysql的小程序. 连接的数据库名称为db_database11,属性如下: 1.创建名为com.pmf.bean的包,包中是名为Product的类,用于封装商品信息. 全部代码如下: package com.pmf.bean; /** * 商品 * */

MATLAB连接MySQL数据库

今天开始看<MATLAB数据分析与挖掘实战>,学习了下用MATLAB连接MySQL数据库,环境win7,32bit,MySQL5.7.12,MATLAB2013B 首先,从这里下载驱动的压缩文件(我选的第一个),解压,将mysql-connector-java-5.1.39-bin.jar放到MATLAB安装文件下(理论上放在其他地方应该也可以,因为之后要指定驱动的路径). 之后,直接执行以下代码即可成功连接,并进行简单的数据转存. %%MySQL数据库导入数据 clear; % 初始化参数

MySQL学习笔记_11_Linux下C++/C连接MySQL数据库(一)

 Linux 下 C++/C 连接 MySQL 数据库(一) 一.连接前准备 原材料:Ubuntu12.04LTS (已经安装了MySQL5.5或者更高级版本,新立得软件包,gcc/g++或者CodeBlosks编译器) 安装了以上的软件包后,我们可以正常使用MySQL完成数据管理工作,但是很多时候我们需要通过编写程序访问MySQL.此时,在程序中需要加载MySQL驱动头文件,但是默认这些驱动包是没有安装的,因此我们需要在新立得中找到"libmysqld-dev"包并安装. 安装完

C++MFC连接MYSQL数据库

今天分享一下VS2013MFC利用mysql自己的api函数来连接MYSQL数据库,数据库的安装在这里不多说,可以找教程,我主要记录一下C++MFC连接数据库.需要说明一点,我使用的VS2013是32位的,所以MYSQL也必须使用32位的,这样不会出现莫名奇妙的错误.接下来开始步骤: 一:项目配置 1.打开mysql的安装路径,找到include文件夹和lib文件夹 如图:    2.打开项目 –> 属性 –>VC++目录  如图:     把include和lib分别添加到包含目录和库目录即

java用JDBC连接MySQL数据库的详细知识点

想实现java用JDBC连接MySQL数据库.需要有几个准备工作: 1.下载Connector/J的库文件,下载Connector/J的官网地址:http://www.mysql.com/downloads/connector/j/ 2.MySQL数据库安装包的下载和安装:http://pan.baidu.com/s/1sleNubV 3.在dos命令窗口中对mysql进行配置和使用.配置如下: ①在开始菜单的搜索框中输入"cmd"命令. ②把安装mysql软件的路径到bin目录下输入

eclipse连接MySQL数据库的步骤

java可以兼容目前市面上所有类型的数据库,主要是因为提供了两个接口,一个用于连接目标数据库,一个用于向数据库中传输SQL命令. Connection接口——连接目标数据库: Statement  接口——向目标数据传送SQL命令: 这里主要介绍Eclipse连接MySqL数据库的流程(MySQL以5.7版本为例): 1.导入JDBC驱动包 Class.forName("com.mysql.jdbc.Driver"); 2.获取连接对象(连接目标数据库) Connection conn