【MySQL】mysql-connector-cpp使用

【MySQL】mysql-connector-cpp使用

mysql-connector-cpp 地址

X DevAPI - 数据库连接池

没有写多线程测试,只是写了一个简单的demo跑了下。

有两个问题没有仔细考察:

  • 当线程池中没有连接可用时,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,
);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值