【MySQL】mysql-connector-cpp使用
X DevAPI - 数据库连接池
没有写多线程测试,只是写了一个简单的demo跑了下。
X DevAPI提供了mysql的数据库连接池的api:2.2.3 Connecting to a Single MySQL Server Using Connection Pooling
代码中涉及到表的增删改查的api,可参考3.1 CRUD Operations Overview
有两个问题没有仔细考察:
当线程池中没有连接可用时,
cli.getSession();
是否阻塞。我想应该时阻塞的?Client的接口文档中也没写,只能到源码中找答案了。抛出异常该如何接收和处理。抛出的异常类型是
mysqlx::Error
// compile: g++ test-x-plugin.cpp -o test-x-plugin -I /usr/include/mysql-cppconn-8/ -lmysqlcppconn8
#include <mysqlx/xdevapi.h>
#include <iostream>
#include <list>
/**
* 数据库连接,并给表插入一列
*/
void unit_test_1(void) {
mysqlx::Session sess("localhost", 33060, "dacao", "qwert");
mysqlx::Schema db= sess.getSchema("message_board");
mysqlx::Table tb = db.getTable("message");
tb.insert("username", "message")
.values("lisi","hello world")
.execute();
}
/**
* 数据库连接池
*/
void unit_test_2(void) {
using namespace mysqlx;
// Client cli("user:password@host_name/db_name", ClientOption::POOL_MAX_SIZE, 7);
Client cli("dacao:qwert@127.0.0.1", ClientOption::POOL_MAX_SIZE, 7);
Session sess = cli.getSession();
mysqlx::Schema db= sess.getSchema("message_board");
mysqlx::Table tb = db.getTable("message");
mysqlx::RowResult result = tb.select("*").execute();
std::list<mysqlx::Row> rows = result.fetchAll();
std::cout<<"name "<<"password "<<std::endl;
for(auto row : rows) {
std::cout<<row[0]<<" "<<row[1]<<std::endl;
}
cli.close(); // close all Sessions
}
int main(int argc, char** argv)
{
unit_test_1();
unit_test_2();
}
上面代码需要提下的是,连接数据库的参考。
- 第一种连接是
mysqlx::Session sess("localhost", 33060, "dacao", "qwert");
。 - 第二种连接是
Client cli("dacao:qwert@127.0.0.1/message_board", ClientOption::POOL_MAX_SIZE, 7);。
这两种构造过程是类似的,可以看下xdevapi.h源文件中的注释。
Session from_uri("mysqlx://user:pwd@host:port/db?ssl-mode=disabled");
Session from_options("host", port, "user", "pwd", "db");
Session from_option_list(
SessionOption::USER, "user",
SessionOption::PWD, "pwd",
SessionOption::HOST, "host",
SessionOption::PORT, port,
SessionOption::DB, "db",
SessionOption::SSL_MODE, SSLMode::DISABLED
);
Client from_uri("mysqlx://user:pwd\@host:port/db?ssl-mode=disabled");
Client from_options("host", port, "user", "pwd", "db");
Client from_option_list(
SessionOption::USER, "user",
SessionOption::PWD, "pwd",
SessionOption::HOST, "host",
SessionOption::PORT, port,
SessionOption::DB, "db",
SessionOption::SSL_MODE, SSLMode::DISABLED
ClientOption::POOLING, true,
ClientOption::POOL_MAX_SIZE, 10,
ClientOption::POOL_QUEUE_TIMEOUT, 1000,
ClientOption::POOL_MAX_IDLE_TIME, 500,
);
,
ClientOption::POOL_MAX_SIZE, 10,
ClientOption::POOL_QUEUE_TIMEOUT, 1000,
ClientOption::POOL_MAX_IDLE_TIME, 500,
);