在Linux下,如何实现C++操做Mysql数据库?

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

链接MySQL数据库有两种方法:第一种是使用ADO链接,不过这种只适合Windows平台;第二种是使用MySQL本身的C API函数链接数据库。我是在Linux平台下开发,因此就采用第二种方法,有不少Api函数,可是经常使用的就几个,我也是就用到其中的几个。ios


 

API函数

1.mysql_real_connect()

链接一个mysql服务器程序员

MYSQL *mysql_real_connect (MYSQL *mysql,sql

const char*host,数据库

const char*user,编程

const char*passwd,数组

const char*db,服务器

unsigned intport,socket

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。


 

简单的学生信息管理代码

光看也记不住啊,就用这些函数写了一个学生信息管理界面,下面是代码:

#include <iostream>

#include <string>

#include <stack>

#include <algorithm>

#include <sstream>

#include <mysql/mysql.h>

#include <unistd.h>

 

usingnamespacestd;

 

 

MYSQL mysql;  

MYSQL_ROW row; 

MYSQL_FIELD* field = NULL;      

MYSQL_RES* result;                                                 

 

string IntToStr(intnum)

{        

  stringstream ss;

  ss.clear();

  ss << num;

  returnss.str();

}

 

voidAdd()

{

  string fname,fsex,ftel,faddr;

  intfage;

  charchoice;

  do

  {

  ┊  cout << "请依次输入如下信息:"<< endl;

  ┊  cout << "\nName: ";cin >> fname;

  ┊  cout << "\nSex: ";cin >> fsex;

  ┊  cout << "\nAge: "; cin >> fage;

  ┊  cout << "\nTel: "; cin >> ftel;

  ┊  cout << "\nAddr: "; cin >> faddr;

 

  ┊  string sql = "INSERT INTO Infor (name,sex,tel,addr,age) values('"+fname+"','"+fsex+"','"+ftel+"','"+faddr+"',   "+IntToStr(fage)+");";

  ┊  //string sql = "INSERT INTO Infor (name,sex,age,tel,addr) values('小红','女',18,'13333333333',          '陕西省西安市雁塔区');";

 

  ┊  mysql_query(&mysql,sql.c_str());

  ┊  ┊              

  ┊  cout << "是否继续添加(y/n)?: ";

  ┊  cin >> choice;                                               

  }while(choice == 'y');      

 

}                  

 

voidSelect()            

{                  

  intid;             

  cout << "请输入要查询学生的学号: ";

  cin >> id;            

 

  string sql = "SELECT * FROM Infor WHERE id = "+IntToStr(id)+";";

  mysql_query(&mysql,sql.c_str());

 

  result = mysql_store_result(&mysql);

  if(result == NULL)

  ┊  cout << "fail\n";

 

  for(inti=0; i<mysql_num_fields(result); i++)

  {        

  ┊  field = mysql_fetch_field_direct(result,i);

  ┊  cout << field->name << "\t\t";

  }               

  cout << endl;         

 

  row = mysql_fetch_row(result); 

  while(row != NULL)       

  {               

  ┊  for(inti=0; i<mysql_num_fields(result); i++)

  ┊  {             

  ┊  ┊  cout << row[i] << "\t\t";                                        

  ┊  }             

  ┊  cout << endl;       

  ┊  row = mysql_fetch_row(result);

  }               

}                 

 

 

voidUpdate()           

{                 

  intid;            

  charchoice;          

  string newaddr;        

  ┊  cout << "请输入要修改同窗的学号: ";

  ┊  cin >> id;         

  ┊  cout << endl << "请输入修改后的地址: ";

  ┊  cin >> newaddr;

  ┊  string sql = "UPDATE Infor SET addr = '"+newaddr+"'WHERE id= "+IntToStr(id)+"; ";

  ┊  mysql_query(&mysql,sql.c_str());                                      

  ┊    

}      

 

intmain() 

{      

  charchoice[5];

  mysql_init(&mysql);

  /*链接数据库*/

  if(!mysql_real_connect(&mysql,"localhost","root","dxm242012","Student",0,NULL,0))

  {    

  ┊  cout << "connect fial\n";

  ┊  return-1;

  }    

 

  while(atoi(choice) != 'q')

  {    

  ┊  sleep(4);

  ┊  system("clear");

  ┊  cout << "1.添加学生信息"<< endl;

  ┊  cout << "2.查询学生信息"<< endl;

  ┊  cout << "3.修改学生信息"<< endl;

 

  ┊  cin >> choice;

 

  ┊  cout << choice << endl;

  ┊  switch(atoi(choice))

  ┊  { 

  ┊  ┊  case1:

  ┊  ┊  ┊  Add();

  ┊  ┊  ┊  break;

  ┊  ┊  case2:

  ┊  ┊  ┊  Select();

  ┊  ┊  ┊  break;

  ┊  ┊  case3:

  ┊  ┊  ┊  Update();

  ┊  ┊  ┊  break;

  ┊  ┊  default:

  ┊  ┊  ┊  break;

  ┊  } 

  }

 

  mysql_close(&mysql);

  return0;

}

 


 

C++封装MyDB类

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

#ifndef _MYDB_H

#define _MYDB_H

 

#include <string>

#include <iostream>

#include <mysql/mysql.h>

usingnamespacestd;

 

classMyDB

{

 

public:

  MyDB();

  ~MyDB();

  boolInitDB(string host,string user,string pwd,string dbname);                         

  boolExeSQL(string sql);

private:

  MYSQL* mysql;

  MYSQL* mysql;

  MYSQL_ROW row;

  MYSQL_RES* result;

  MYSQL_FIELD* field;                                               

};

#endif     

 

#include <iostream>

#include <string>

#include <stack>

#include <algorithm>  

#include <mysql/mysql.h>

#include "myDB.h"

 

usingnamespacestd;

 

MyDB::MyDB()  

{

  mysql = mysql_init(NULL);

  if(mysql == NULL)

  {

  ┊  cout << "Error: "<< mysql_error(mysql);

  ┊  exit(-1);

  }     

}

 

MyDB::~MyDB()

{                                                          

  if(!mysql)

  {

  ┊  mysql_close(mysql);

  }

}

 

boolMyDB::InitDB(string host,string user,string pwd,string dbname)

{

  /*链接数据库*/

  if(!mysql_real_connect(mysql,host.c_str(),user.c_str(),pwd.c_str(),dbname.c_str(),0,NULL,0))

  {

  ┊  cout << "connect fial: "<< mysql_error(mysql);

  ┊  exit(-1);

  }

  returntrue;

}

 

boolMyDB::ExeSQL(string sql)

{

  /*执行失败*/

  if(mysql_query(mysql,sql.c_str()))

  {

  ┊  cout << "query fail: "<< mysql_error(mysql);

  ┊  exit(1);                                                  

  }

 

  else

  {

  ┊  /*获取结果集*/

  ┊  result = mysql_store_result(mysql);

 

  ┊  intfieldnum = mysql_num_fields(result);

  ┊  for(inti=0; i<fieldnum; i++)

  ┊  {

  ┊  ┊  row = mysql_fetch_row(result);

  ┊  ┊  if(row <= 0)

  ┊  ┊  ┊  break;

  ┊  ┊  for(intj=0; j<fieldnum; j++)

  ┊  ┊  {

  ┊  ┊  ┊  cout << row[j] << "\t\t";

  ┊  ┊  }

  ┊  ┊  cout << endl;

  ┊  }

  ┊  mysql_free_result(result);

  }

  returntrue;

}

 

#include <iostream>

#include <string>

#include <stack>

#include <algorithm>

#include <mysql/mysql.h>

#include "myDB.h"

 

usingnamespacestd;

 

 

intmain()

{  

  MyDB db;

  db.InitDB("localhost","root","xxxxxx","Student");

  db.ExeSQL("SELECT * FROM Infor;");

  return0;

}  

如下是运行结果:


 

下面是遇到的问题: 

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(intnum)

{        

  stringstream ss;

  ss.clear();

  ss << num;

  returnss.str();

}

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

文章来源:做者——Tanswer_ 

今天文章就介绍到这了,有什么问题欢迎评论区留言。


 

最后,若是你也想成为程序员,想要快速掌握编程,赶忙加入学习企鹅圈子

里面有资深专业软件开发工程师,在线解答你的全部疑惑~编程语言入门“so easy”

编程学习书籍:


 

编程学习视频:

相关文章
相关标签/搜索