日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > 数据库 >内容正文

数据库

Linux MySQL Connector/C++ 编程实例

發(fā)布時(shí)間:2025/4/5 数据库 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Linux MySQL Connector/C++ 编程实例 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

本篇文章介紹如何在Linux平臺(tái)使用Connector/C++ 連接數(shù)據(jù)庫(kù),假定MySQL已經(jīng)安裝完成。如果還沒(méi)有安裝MySQL,請(qǐng)先安裝。MySQL版本:8.0.19

目錄

1. 安裝Connector/C++

2. 編寫(xiě)代碼

3. 創(chuàng)建數(shù)據(jù)庫(kù)

4. 可能遇到的編譯問(wèn)題解決方案

參考文檔:


示例是一個(gè)圖書(shū)館管理系統(tǒng),擁有添加、刪除、修改、查詢(xún)功能。先看下實(shí)現(xiàn)效果圖:

在看具體代碼之前,先看下示例的設(shè)計(jì)文檔:

下面進(jìn)入正式教程:

1. 安裝Connector/C++

下載地址(https://dev.mysql.com/downloads/connector/cpp/)。

下載解壓完成后,如下圖:

lib64存放庫(kù)文件,include存放頭文件。

2. 編寫(xiě)代碼

新建library目錄。然后在該目錄下新建三個(gè)文件。library_main.cpp, library_sql.h, library_book.h Makefile?。代碼如下:

library_main.cpp

/** Desc: Linux c++ MySQL 示例,圖書(shū)館管理系統(tǒng),主程序* Author: mason* Date: 20200203*/#include "library_book.h" #include "library_sql.h"#define LIBRARY_ADD_BOOK 1 // 添加 #define LIBRARY_DELETE_BOOK 2 // 刪除 #define LIBRARY_UPDATE_BOOK 3 // 修改 #define LIBRARY_QUERY_BOOK 4 // 查詢(xún) #define LIBRARY_QUIT 5 // 退出// MySQL單例類(lèi)靜態(tài)變量初始化 sql::Driver* sql_loader::driver = nullptr; sql::Connection* sql_loader::con = nullptr; sql::Statement* sql_loader::stmt = nullptr; sql::ResultSet* sql_loader::res = nullptr; bool sql_loader::init = false;// 系統(tǒng)使用說(shuō)明 void Usage() {cout<<"\n歡迎使用圖書(shū)管理系統(tǒng)\n""1:添加圖書(shū)\n""2:刪除圖書(shū)\n""3:修改圖書(shū)\n""4:查詢(xún)圖書(shū)\n""5:退出系統(tǒng)\n"<<endl;return ; }// 讀取圖書(shū)信息 void ReadBook(Book &new_book) {cout<<"請(qǐng)輸入添加的書(shū)名:";cin>>new_book.book_name;cout<<"請(qǐng)輸入作者:";cin>>new_book.author;//cout<<"[DEBUG]"<<author<<endl;cout<<"請(qǐng)輸入價(jià)格:";cin>>new_book.price;cout<<"請(qǐng)輸入數(shù)量:";cin>>new_book.quantity;return ; }int main() {bool is_quit = false;int op_code = -1, book_id;string book_name, author;unsigned int price, quantity;Book new_book;vector<Book> book_list;// 主循環(huán)while (!is_quit){Usage();cout<<"請(qǐng)輸入你的選擇:";cin>>op_code;switch (op_code){// 添加操作case LIBRARY_ADD_BOOK:// 讀取圖書(shū)信息ReadBook(new_book);sql_loader::add(new_book);break;// 刪除操作case LIBRARY_DELETE_BOOK: sql_loader::delete_book();break;// 修改操作case LIBRARY_UPDATE_BOOK: cout<<"請(qǐng)輸入待修改的編號(hào):";cin>>new_book.id;ReadBook(new_book);sql_loader::update(new_book);break; // 查詢(xún)操作case LIBRARY_QUERY_BOOK: sql_loader::query(book_list);// 打印查詢(xún)結(jié)果cout << "------------- 查詢(xún)開(kāi)始 ----------------" <<endl;for (auto &iter : book_list){ cout <<"編號(hào): "<< iter.id << endl;cout <<"書(shū)名: "<< iter.book_name << endl;cout <<"作者: "<< iter.author << endl;cout <<"數(shù)量: "<< iter.quantity << endl;cout <<"價(jià)格: "<< iter.price << endl;cout << "-----------------------------" <<endl;} cout << "------------- 查詢(xún)結(jié)束 ----------------" <<endl;// 清空上次查詢(xún)結(jié)果book_list.erase(book_list.begin(), book_list.end());break;// 退出系統(tǒng) case LIBRARY_QUIT:is_quit = true;break; default:cout<<"未識(shí)別的操作:"<<op_code<<endl;break;}}cout<<"感謝使用"<<endl;return 0; }

library_book.h

/** Desc: Linux c++ MySQL 示例,圖書(shū)館管理系統(tǒng),圖書(shū)類(lèi)* Author: mason* Date: 20200203*/#pragma once #include <string> #include <iostream>using namespace std;class Book {public:int id; // 圖書(shū)編號(hào)string book_name; // 書(shū)名string author; // 作者unsigned int price; // 價(jià)格unsigned int quantity; // 數(shù)量public:// 默認(rèn)構(gòu)造函數(shù)Book(){}// 含參構(gòu)造函數(shù)Book(string book_name, string author, int price, int quantity, int book_id = 0):book_name(book_name),author(author),price(price),quantity(quantity), id(book_id){}// 析構(gòu)函數(shù) ~Book(){} };

library_sql.h

/** Desc: Linux c++ MySQL 示例,圖書(shū)館管理系統(tǒng),MySQL單例* Author: mason* Date: 20200203*/#pragma once#include <vector> #include "library_book.h" #include <mysql_connection.h>#include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h>#define SQL_QUERY_ALL 0 // 查詢(xún)所有 #define SQL_QUERY_BY_AUTHOR 1 // 查詢(xún)作者 #define SQL_QUERY_BY_ID 2 // 查詢(xún)編號(hào) #define SQL_QUERY_BY_BOOK_NAME 3 // 查詢(xún)書(shū)名#define SQL_DELETE_ALL 0 // 刪除所有 #define SQL_DELETE_BY_AUTHOR 1 // 刪除作者 #define SQL_DELETE_BY_ID 2 // 刪除編號(hào) #define SQL_DELETE_BY_BOOK_NAME 3 // 刪除書(shū)名using namespace std;class sql_loader {public:static sql::Driver *driver;static sql::Connection *con;static sql::Statement *stmt;static sql::ResultSet *res;static bool init;// sql 初始化static void sql_loader_init(){if (sql_loader::init){cout<<"sql 已經(jīng)完成初始化"<<endl;return ;}/* Create a connection */driver = get_driver_instance();// 密碼和用戶(hù)名con = driver->connect("tcp://127.0.0.1:3306", "root", "123456");/* Connect to the MySQL test database ,數(shù)據(jù)庫(kù)名*/con->setSchema("library");init = true;cout<<"sql 初始化成功"<<endl;return ;}// 添加圖書(shū)static void add(Book &new_book){// SQL初始化sql_loader_init();// 創(chuàng)建并構(gòu)造sql語(yǔ)句,用完后手動(dòng)刪除stmt = con->createStatement();string sql_cmd = "INSERT INTO books(name, author, price, quantity) VALUES ('";sql_cmd.append(new_book.book_name);sql_cmd.append("','");sql_cmd.append(new_book.author);sql_cmd.append("', ");sql_cmd.append(to_string(new_book.price));sql_cmd.append(", ");sql_cmd.append(to_string(new_book.quantity));sql_cmd.append(")");cout<<"insert cmd : "<<sql_cmd<<endl;try{stmt->execute(sql_cmd);} catch (sql::SQLException &e) {cout << "# ERR: SQLException in " << __FILE__;cout << "(" << __FUNCTION__ << ") on line "<< __LINE__ << endl;cout << "# ERR: " << e.what();cout << " (MySQL error code: " << e.getErrorCode();cout << ", SQLState: " << e.getSQLState() << " )" << endl;}// 刪除資源delete stmt;return ;}// 修改圖書(shū)static void update(Book& new_book){// SQL初始化sql_loader_init();// 創(chuàng)建并構(gòu)造sql語(yǔ)句,用完后手動(dòng)刪除 stmt = con->createStatement();string sql_cmd = "update books set name='";sql_cmd.append(new_book.book_name);sql_cmd.append("', author='");sql_cmd.append(new_book.author);sql_cmd.append("', price=");sql_cmd.append(to_string(new_book.price));sql_cmd.append(", quantity=");sql_cmd.append(to_string(new_book.quantity));sql_cmd.append(" where id=");sql_cmd.append(to_string(new_book.id));cout<<"update cmd : "<<sql_cmd<<endl;try{stmt->execute(sql_cmd);} catch (sql::SQLException &e) {cout << "# ERR: SQLException in " << __FILE__;cout << "(" << __FUNCTION__ << ") on line "<< __LINE__ << endl;cout << "# ERR: " << e.what();cout << " (MySQL error code: " << e.getErrorCode();cout << ", SQLState: " << e.getSQLState() << " )" << endl;}// 釋放資源delete stmt;return ; }// 刪除圖書(shū)static void delete_book(){int op_code = -1, book_id;string author, book_name;string sql_cmd = "delete from books";cout<<"請(qǐng)輸入刪除方式:\n""0: 刪除所有圖書(shū)\n""1: 刪除指定作者\(yùn)n""2: 刪除指定編號(hào)\n""3: 刪除指定圖書(shū)"<<endl;cin>>op_code;switch (op_code){case SQL_DELETE_ALL:break;case SQL_DELETE_BY_AUTHOR:cout<<"請(qǐng)輸入要?jiǎng)h除的作者:";cin>>author;sql_cmd.append(" where author='");sql_cmd.append(author);sql_cmd.append("'");break;case SQL_DELETE_BY_ID:cout<<"請(qǐng)輸入要?jiǎng)h除的編號(hào):";cin>>book_id;sql_cmd.append(" where id=");sql_cmd.append(to_string(book_id)); break;case SQL_DELETE_BY_BOOK_NAME:cout<<"請(qǐng)輸入要?jiǎng)h除的書(shū)名:";cin>>book_name;sql_cmd.append(" where name='");sql_cmd.append(book_name);sql_cmd.append("'"); break;default:cout<<"不存在 "<<op_code<<" 對(duì)應(yīng)的刪除方式,刪除失敗"<<endl;return ;}cout<<"delete cmd : "<<sql_cmd<<endl;// 初始化SQLsql_loader_init();// 創(chuàng)建并構(gòu)造sql語(yǔ)句,用完后手動(dòng)刪除 stmt = con->createStatement();try{// 執(zhí)行SQL語(yǔ)句stmt->execute(sql_cmd);// 釋放資源delete stmt;} catch (sql::SQLException &e) {cout << "# ERR: SQLException in " << __FILE__;cout << "(" << __FUNCTION__ << ") on line "<< __LINE__ << endl;cout << "# ERR: " << e.what();cout << " (MySQL error code: " << e.getErrorCode();cout << ", SQLState: " << e.getSQLState() << " )" << endl;}return ; }// 查詢(xún)圖書(shū)static void query(vector<Book>& book_list){int op_code = -1, book_id;string author, book_name;string sql_cmd = "select id, name, author, quantity, price from books";cout<<"請(qǐng)輸入查詢(xún)方式:\n""0: 查詢(xún)所有\(zhòng)n""1: 查詢(xún)作者\(yùn)n""2: 查詢(xún)編號(hào)\n""3: 查詢(xún)書(shū)名"<<endl;cin>>op_code;switch (op_code){case SQL_QUERY_ALL:break;case SQL_QUERY_BY_AUTHOR:cout<<"請(qǐng)輸入要查詢(xún)的作者:";cin>>author;sql_cmd.append(" where author='");sql_cmd.append(author);sql_cmd.append("'");break;case SQL_QUERY_BY_ID:cout<<"請(qǐng)輸入要查詢(xún)的編號(hào):";cin>>book_id;sql_cmd.append(" where id=");sql_cmd.append(to_string(book_id)); break;case SQL_QUERY_BY_BOOK_NAME:cout<<"請(qǐng)輸入要查詢(xún)的書(shū)名:";cin>>book_name;sql_cmd.append(" where name='");sql_cmd.append(book_name);sql_cmd.append("'"); break;default:cout<<"不存在 "<<op_code<<" 對(duì)應(yīng)的查詢(xún)方式,查詢(xún)失敗"<<endl;return ;}cout<<"query cmd : "<<sql_cmd<<endl;// 初始化SQL sql_loader_init();// 創(chuàng)建并構(gòu)造sql語(yǔ)句,用完后手動(dòng)刪除 stmt = con->createStatement();try{// 執(zhí)行查詢(xún)r(jià)es = stmt->executeQuery(sql_cmd);while (res->next()) {/* Access column data by alias or column name */cout << res->getInt("id") << res->getString("name") << res->getString("author") << res->getInt("quantity") << endl;book_list.push_back(Book(res->getString("name"), res->getString("author"), res->getInt("price"), res->getInt("quantity"), res->getInt("id")));/* Access column data by numeric offset, 1 is the first column *///cout << res->getString(1) << endl;}// 資源釋放delete res;delete stmt;} catch (sql::SQLException &e) {cout << "# ERR: SQLException in " << __FILE__;cout << "(" << __FUNCTION__ << ") on line "<< __LINE__ << endl;cout << "# ERR: " << e.what();cout << " (MySQL error code: " << e.getErrorCode();cout << ", SQLState: " << e.getSQLState() << " )" << endl;}return ;}private:sql_loader(){} };

Makefile,編譯路徑根據(jù)實(shí)際路徑做調(diào)整。

default:g++ -std=c++11 -I /data/home/code/github/cpp-test/mysql/include/jdbc -L /data/home/code/github/cpp-test/mysql/lib64 library_main.cpp -o app -lmysqlcppconn clean:rm -rf app

3. 創(chuàng)建數(shù)據(jù)庫(kù)

// 創(chuàng)建數(shù)據(jù)庫(kù) create database library; // 創(chuàng)建圖書(shū)表 create table books (id int not null auto_increment,name varchar(1024) not null,author varchar(1024) not null,price int not null default 0,quantity int not null default 1,primary key(id) )DEFAULT CHARACTER SET = utf8;

4. 可能遇到的編譯問(wèn)題解決方案

1.?jdbc/mysql_connection.h:37:32: fatal error: boost/shared_ptr.hpp: No such file or directory

解決方式是安裝boost-devel,yum安裝命令如下,ubuntu或者其它平臺(tái)請(qǐng)自行搜索。

yum install boost-devel

2.?# ERR: Host '127.0.0.1' is not allowed to connect to this MySQL server (MySQL error code: 1130, SQLState: HY000 )

無(wú)法連接MySQL,先查看本地msyqld是否允許以及能否登陸,都正常可能是權(quán)限問(wèn)題,參考這篇博客:

https://blog.csdn.net/eric_sunah/article/details/18567091

?

參考文檔:

1.?https://docs.oracle.com/cd/E17952_01/connector-cpp-1.1-en

總結(jié)

以上是生活随笔為你收集整理的Linux MySQL Connector/C++ 编程实例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。