用C++操作MySQL数据库,linux下需要用到头文件 #include <mysql/mysql.h>
说明:https://blog.csdn.net/Linux\_ever/article/details/50651513
为了使用方便,写了一个MyDataBase类,提供一些基本的数据库操作,和一个query函数用来提供自定义查询
1 #pragma once
2
3 #include <mysql/mysql.h>
4 #include <string>
5 #include <vector>
6 #include <iostream>
7
8 using std::string;
9 using std::vector;
10
11 class MyDataBase
12 {
13 private:
14 MYSQL *sql;
15 MYSQL_RES *res;
16 MYSQL_ROW row;
17 bool connect_flag;
18 void showres();
19 public:
20 MyDataBase();
21 MyDataBase(MYSQL *mysql);
22 ~MyDataBase();
23 void connect(const string host, const string user, const string password,
24 const string database = "mysql", unsigned int port = 0,
25 const char *unix_socket = nullptr, unsigned long client_flag = 0);
26 void disconnect();
27 void showdb();
28 void createdb(const string &database);
29 void usedb(const string &database);
30 void deletedb(const string &database);
31 void showtb();
32 void createtb(const string &table, const string &elements);
33 vector<vector<string>> selectitem(const string &table, const string &value);
34 vector<vector<string>> selectitem(const string &table, const string &value, const string &limits);
35 void insertitem(const string &table, const string &value);
36 void insertitem(const string &table, const string &value, const string &col);
37 void deleteitem(const string &table, const string &value);
38 void updateitem(const string &table, const string &value, const string &limits);
39 void query(const string &command);
40 };
详细代码:https://github.com/Zzzy14/Function/tree/master/MyDataBase
Makefile:
1 all : main
2 main : main.o MyDataBase.o
3 g++ -o main main.o MyDataBase.o -l mysqlclient
4 MyDataBase.o : MyDataBase.cpp
5 g++ -std=c++11 -c MyDataBase.cpp
6 main.o : main.cpp
7 g++ -std=c++11 -c main.cpp
8 clean:
9 rm *.o
测试代码:
1 #include "MyDataBase.h"
2 #include <vector>
3 using namespace std;
4
5 int main(int argc, char const *argv[])
6 {
7 MyDataBase mdb;
8 mdb.connect("localhost", "root", "1234");
9 mdb.createdb("mydb");
10 mdb.usedb("mydb");
11 mdb.createtb("tst", "id int default 0, password varchar(255) default \"000000\"");
12 mdb.insertitem("tst", "12345, \"hshsh\"");
13 mdb.insertitem("tst", "\"hshsh\"", "password");
14 mdb.insertitem("tst", "12346", "id");
15 mdb.updateitem("tst", "password = 99999", "id = 12346");
16 vector<vector<string>> ret = mdb.selectitem("tst", "*");
17 for (auto temp: ret) {
18 for (auto &str: temp)
19 cout << str << " ";
20 cout << endl;
21 }
22 mdb.deleteitem("tst", "id = 0");
23 ret = mdb.selectitem("tst", "*");
24 for (auto temp: ret) {
25 for (auto &str: temp)
26 cout << str << " ";
27 cout << endl;
28 }
29 mdb.deletedb("mydb");
30 mdb.disconnect();
31 return 0;
32 }
输出: