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     {
 39cout << "请依次输入以下信息:" << endl;
 40cout << "\nName: ";cin >> fname;
 41cout << "\nSex: ";cin >> fsex;
 42cout << "\nAge: "; cin >> fage;
 43cout << "\nTel: "; cin >> ftel;
 44cout << "\nAddr: "; cin >> faddr;
 45  
 46string 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     ┊   ┊                              
 51cout << "是否继续添加(y/n)?: ";
 52cin >> 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)
 68cout << "fail\n";
 69                       
 70     for(int i=0; i<mysql_num_fields(result); i++)
 71     {                 
 72     ┊   field = mysql_fetch_field_direct(result,i);
 73cout << field->name << "\t\t";
 74     }                                
 75     cout << endl;                    
 76                                      
 77     row = mysql_fetch_row(result);   
 78     while(row != NULL)               
 79     {                                
 80for(int i=0; i<mysql_num_fields(result); i++)
 81     ┊   {                            
 82     ┊   ┊   cout << row[i] << "\t\t";                                                                                 
 83     ┊   }                            
 84cout << endl;                
 85     ┊   row = mysql_fetch_row(result);
 86     }                                
 87 }                                    
 88                                      
 89                                      
 90 void Update()                        
 91 {                                    
 92     int id;                          
 93     char choice;                     
 94     string newaddr;                  
 95cout << "请输入要修改同学的学号: ";
 96cin >> id;                   
 97cout << endl << "请输入修改后的地址: ";
 98cin >> newaddr;
 99string sql = "UPDATE Infor SET addr = '"+newaddr+"'WHERE id= "+IntToStr(id)+"; ";
100     ┊   mysql_query(&mysql,sql.c_str());                                                                              
101102 }             
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     {         
113cout << "connect fial\n";
114return -1;
115     }         
116               
117     while(atoi(choice) != 'q')
118     {         
119     ┊   sleep(4);
120     ┊   system("clear");
121cout << "1.添加学生信息" << endl;
122cout << "2.查询学生信息" << endl;
123cout << "3.修改学生信息" << endl;
124                                                                                                                       
125cin >> choice;
126      
127cout << choice << endl;
128switch(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     {
 22cout << "Error: " << mysql_error(mysql);
 23exit(-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     {
 40cout << "connect fial: " << mysql_error(mysql);
 41exit(-1);
 42     }
 43     return true;
 44 }
 45  
 46 bool MyDB::ExeSQL(string sql)
 47 {
 48     /*执行失败*/
 49     if(mysql_query(mysql,sql.c_str()))
 50     {
 51cout << "query fail: " << mysql_error(mysql);
 52exit(1);                                                                                                      
 53     }
 54  
 55     else
 56     {
 57/*获取结果集*/
 58     ┊   result = mysql_store_result(mysql);
 59  
 60int fieldnum = mysql_num_fields(result);
 61for(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 }      

以下是运行结果:

这里写图片描述

下面是遇到的问题:
1. 编译时出错
没有那个文件或目录
#include<mysql/mysql.h>
^

编译中断。
解决:除了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();
 }

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

  • 14
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值