C++操作Mysql数据库/Linux下

栏目: C++ · 发布时间: 7年前

内容简介:C++操作Mysql数据库/Linux下

想用C++写项目,数据库是必须的,所以这两天学了一下C++操作 Mysql 数据库的方法。也没有什么教程,就是在网上搜的知识,下面汇总一下。

连接MySQL数据库有两种方法:第一种是使用ADO连接,不过这种只适合Windows平台;第二种是使用MySQL自己的C API函数连接数据库。我是在 Linux 平台下开发,所以就采用第二种方法,有很多Api函数,但是常用的就几个,我也是就用到其中的几个。

API函数

1.mysql_real_connect()

连接一个mysql服务器

MYSQL *mysql_real_connect (MYSQL *mysql,

const char *host,

const char *user,

const char *passwd,

const char *db,

unsigned int port,

const char *unix_socket,

unsigned long client_flag)

如果连接成功,返回MYSQL*连接句柄。如果连接失败,返回NULL。对于成功的连接,返回值与第1个参数的值相同

2.mysql_query()

执行指定”以NULL终结的字符串”的 SQL 查询

返回一个结果表,假定查询成功,可以调用 mysql_num_rows() 来查看对应于 SELECT 语句返回了多少行,或者调用 mysql_affected_rows() 来查看对应于 DELETE,INSERT,REPLACE 或 UPDATE 语句影响到了多少行。

3.mysql_store_result()

MYSQL_RES *mysql_store_result(MYSQL *mysql)

检索完整的结果集至客户端。客户端处理结果集最常用的方式是通过调用mysql_store_result(),一次性地检索整个结果集。该函数能从服务器获得查询返回的所有行,并将它们保存在客户端。对于成功检索了数据的每个查询(SELECT、SHOW、DESCRIBE、EXPLAIN、CHECK TABLE等),必须调用mysql_store_result()或mysql_use_result() 。对于其他查询,不需要调用mysql_store_result()或mysql_use_result(),但是如果在任何情况下均调用了mysql_store_result(),它也不会导致任何伤害或性能降低。

4.mysql_num_rows()

返回结果集中的行数。

5.mysql_num_fields()

返回结果集中的字段数,如果失败,则返回 false。

6.mysql_fetch_field()

MYSQL_FIELD* mysql_fetch_field(MYSQL_RES *result);

获取下一个表字段的类型,结束返回NULL。

7.mysql_fetch_row()

MYSQL_ROW mysql_fetch_row(MYSQL_RES *result);

从结果集中获取下一行,成功返回一个数组,值大于0。

8.mysql_fetch_field_direct()

MYSQL_FIELD* mysql_fetch_field_direct(MYSQL_RES *result, int i);

给定字段编号,返回表字段的类型,结束返回NULL。

简单的学生信息管理代码

光看也记不住啊,就用这些函数写了一个学生信息管理界面,唉,去年这时候 C语言 课程设计,当时还不知道用数据库,全用文件写的,知道晚了很后悔啊。。。。下面是代码:

1 /*************************************************************************
  2     > File Name: student.cpp
  3     > Author: Tanswer_ 
  4     > Mail: 98duxm@gmail.com
  5     > Created Time: 2017年05月28日 星期日 16时50分34秒
  6  ************************************************************************/
  7                   
  8 #include <iostream>
  9 #include <string> 
 10 #include <stack>  
 11 #include <algorithm>
 12 #include <sstream>
 13 #include <mysql/mysql.h>
 14 #include <unistd.h>
 15                   
 16 using namespace std;
 17                   
 18                   
 19 MYSQL mysql;      
 20 MYSQL_ROW row;    
 21 MYSQL_FIELD* field = NULL;             
 22 MYSQL_RES* result;                                                                                                    
 23                   
 24 string IntToStr(int num)
 25 {                 
 26     stringstream ss;
 27     ss.clear();
 28     ss << num;
 29     return ss.str();
 30 }
 31                                                                                                                       
 32 void Add()
 33 {
 34     string fname,fsex,ftel,faddr;
 35     int fage;
 36     char choice; 
 37     do
 38     {
 39        cout << "请依次输入以下信息:" << endl;
 40        cout << "\nName: ";cin >> fname;
 41        cout << "\nSex: ";cin >> fsex;
 42        cout << "\nAge: "; cin >> fage;
 43        cout << "\nTel: "; cin >> ftel;
 44        cout << "\nAddr: "; cin >> faddr;
 45  
 46        string sql = "INSERT INTO Infor (name,sex,tel,addr,age) values('"+fname+"','"+fsex+"','"+ftel+"','"+faddr+"',     "+IntToStr(fage)+");";
 47        //string sql = "INSERT INTO Infor (name,sex,age,tel,addr) values('小红','女',18,'13333333333',                    '陕西省西安市雁塔区');";
 48
 49        mysql_query(&mysql,sql.c_str());
 50                                      
 51        cout << "是否继续添加(y/n)?: ";
 52        cin >> choice;                                                                                                
 53     }while(choice == 'y');             
 54                                        
 55 }                                      
 56                                        
 57 void Select()                          
 58 {                                      
 59     int id;                            
 60     cout << "请输入要查询学生的学号: ";
 61     cin >> id;                         
 62                                        
 63     string sql = "SELECT * FROM Infor WHERE id = "+IntToStr(id)+";";
 64     mysql_query(&mysql,sql.c_str());
 65                       
 66     result = mysql_store_result(&mysql);
 67     if(result == NULL)
 68        cout << "fail\n";
 69                       
 70     for(int i=0; i<mysql_num_fields(result); i++)
 71     {                 
 72        field = mysql_fetch_field_direct(result,i);
 73        cout << field->name << "\t\t";
 74     }                                
 75     cout << endl;                    
 76                                      
 77     row = mysql_fetch_row(result);   
 78     while(row != NULL)               
 79     {                                
 80        for(int i=0; i<mysql_num_fields(result); i++)
 81        {                            
 82           cout << row[i] << "\t\t";                                                                                 
 83        }                            
 84        cout << endl;                
 85        row = mysql_fetch_row(result);
 86     }                                
 87 }                                    
 88                                      
 89                                      
 90 void Update()                        
 91 {                                    
 92     int id;                          
 93     char choice;                     
 94     string newaddr;                  
 95        cout << "请输入要修改同学的学号: ";
 96        cin >> id;                   
 97        cout << endl << "请输入修改后的地址: ";
 98        cin >> newaddr;
 99        string sql = "UPDATE Infor SET addr = '"+newaddr+"'WHERE id= "+IntToStr(id)+"; ";
100        mysql_query(&mysql,sql.c_str());                                                                              
101              
102 }             
103               
104               
105 int main()    
106 {             
107     char choice[5];
108               
109     mysql_init(&mysql);
110     /*连接数据库*/
111     if(!mysql_real_connect(&mysql,"localhost","root","dxm242012","Student",0,NULL,0))
112     {         
113        cout << "connect fial\n";
114        return -1;
115     }         
116               
117     while(atoi(choice) != 'q')
118     {         
119        sleep(4);
120        system("clear");
121        cout << "1.添加学生信息" << endl;
122        cout << "2.查询学生信息" << endl;
123        cout << "3.修改学生信息" << endl;
124                                                                                                                       
125        cin >> choice;
126      
127        cout << choice << endl;
128        switch(atoi(choice))
129        {    
130           case 1:
131              Add();
132              break;
133           case 2:
134              Select();
135              break;
136           case 3:
137              Update();
138              break;
139           default:
140              break;
141        }    
142     }
143  
144     mysql_close(&mysql);
145     return 0;
146 }

C++封装MyDB类

后来又把这些函数简单的封装了一下,方便以后直接用。

1 /*************************************************************************
  2     > File Name: myDB.h
  3     > Author: Tanswer_
  4     > Mail: 98duxm@gmail.com
  5     > Created Time: 2017年05月28日 星期日 22时26分22秒
  6  ************************************************************************/
  7   
  8 #ifndef _MYDB_H
  9 #define _MYDB_H
 10   
 11 #include <string>
 12 #include <iostream>
 13 #include <mysql/mysql.h>
 14 using namespace std;
 15   
 16 class MyDB
 17 { 
 18   
 19 public:
 20     MyDB();
 21     ~MyDB();
 22     bool InitDB(string host,string user,string pwd,string dbname);                                                    
 23     bool ExeSQL(string sql);
 24 private:
 25     MYSQL* mysql;
 25     MYSQL* mysql;
 26     MYSQL_ROW row;
 27     MYSQL_RES* result;
 28     MYSQL_FIELD* field;                                                                                               
 29 };
 30   
 31   
 32 #endif
1 /*************************************************************************                                            
  2     > File Name: myDB.cpp
  3     > Author: Tanswer_
  4     > Mail: 98duxm@gmail.com
  5     > Created Time: 2017年05月28日 星期日 22时27分18秒
  6  ************************************************************************/
  7  
  8 #include <iostream>
  9 #include <string>
 10 #include <stack>
 11 #include <algorithm>      
 12 #include <mysql/mysql.h>  
 13 #include "myDB.h"
 14  
 15 using namespace std;
 16  
 17 MyDB::MyDB()     
 18 {
 19     mysql = mysql_init(NULL);
 20     if(mysql == NULL)
 21     {
 22        cout << "Error: " << mysql_error(mysql);
 23        exit(-1);
 24     }           
 25 }
 26  
 27 MyDB::~MyDB()
 28 {                                                                                                                     
 29     if(!mysql)
 30     {
 31        mysql_close(mysql);
 32     }
 33 }
 34  
 35 bool MyDB::InitDB(string host,string user,string pwd,string dbname)
 36 {
 37     /*连接数据库*/
 38     if(!mysql_real_connect(mysql,host.c_str(),user.c_str(),pwd.c_str(),dbname.c_str(),0,NULL,0))
 39     {
 40        cout << "connect fial: " << mysql_error(mysql);
 41        exit(-1);
 42     }
 43     return true;
 44 }
 45  
 46 bool MyDB::ExeSQL(string sql)
 47 {
 48     /*执行失败*/
 49     if(mysql_query(mysql,sql.c_str()))
 50     {
 51        cout << "query fail: " << mysql_error(mysql);
 52        exit(1);                                                                                                      
 53     }
 54  
 55     else
 56     {
 57        /*获取结果集*/
 58        result = mysql_store_result(mysql);
 59  
 60        int fieldnum = mysql_num_fields(result);
 61        for(int i=0; i<fieldnum; i++)
 62        {
 63           row = mysql_fetch_row(result);
 64           if(row <= 0)
 65              break;
 66           for(int j=0; j<fieldnum; j++)
 67           {
 68              cout << row[j] << "\t\t";
 69           }
 70           cout << endl;
 71        }
 72        mysql_free_result(result);
 73     }
 74     return true;
 75 }
1 /*************************************************************************                                            
  2     > File Name: main.cpp
  3     > Author: Tanswer_
  4     > Mail: 98duxm@gmail.com
  5     > Created Time: 2017年05月28日 星期日 22时53分43秒
  6  ************************************************************************/
  7        
  8 #include <iostream>
  9 #include <string>
 10 #include <stack>
 11 #include <algorithm>
 12 #include <mysql/mysql.h>
 13 #include "myDB.h"
 14        
 15 using namespace std;
 16        
 17        
 18 int main()
 19 {      
 20     MyDB db;
 21     db.InitDB("localhost","root","xxxxxx","Student");
 22     db.ExeSQL("SELECT * FROM Infor;");
 23     return 0;
 24 }

以下是运行结果:

C++操作Mysql数据库/Linux下

下面是遇到的问题:

1. 编译时出错

没有那个文件或目录

#include
   
     

                  ^
   

编译中断。

解决:除了mysql-client和mysql-server,又安装了mysql-devel,然后就解决了。

2. 自定义的变量传入sql语句时,出现问题

在网上查找到这样一种格式,

string sql = "INSERT INTO Infor (name,sex,tel,addr,age) values('"+fname+"','"+fsex+"','"+ftel+"','"+faddr+"', "+IntToStr(fage)+");"; 然后string类型的可以成功,整型的变量还是不行,我又写了个函数把int转为string。

string IntToStr(int num)
 {                 
     stringstream ss;
     ss.clear();
     ss << num;
     return ss.str();
 }

大概就是这样,门卫大叔很凶,我也很绝望,就写到这吧,有问题再补充。


以上所述就是小编给大家介绍的《C++操作Mysql数据库/Linux下》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

HTTP Essentials

HTTP Essentials

Stephen A. Thomas、Stephen Thomas / Wiley / 2001-03-08 / USD 34.99

The first complete reference guide to the essential Web protocol As applications and services converge and Web technologies not only assume HTTP but require developers to manipulate it, it is be......一起来看看 《HTTP Essentials》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具