mysql connector c++ 1.1 API初步体验

1,常用的头文件

#include <mysql_connection.h>
#include <mysql_driver.h>
#include <cppconn/driver.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/resultset.h>

2,创建连接

#define DBHOST "tcp://127.0.0.1:3306"
#define USER "username"
#define PASSWORD "pwd" sql::mysql::MySQL_Driver *driver;
sql::Connection *con;
sql::Statement *stmt; driver = sql::mysql::get_mysql_driver_instance();
con = driver->connect(DBHOST, USER, PASSWORD);

3,选择要使用的database的名字

con->setSchema("database_name");

4,设置连接的属性,例子是设置连接的字符集

con->setClientOption("characterSetResults", "utf8");

5,判断连接是否建立成功

if(con->isValid()){
std::cout << "connected!" << std::endl;
}

6,执行insert语句

sql::PreparedStatement* pstmt;
std::string sqlOp="insert into user(name,nickname,password, phone) values(?,?,?,?)";
pstmt=con->prepareStatement(sqlOp);
pstmt->setString(1,"李四2");
pstmt->setString(2,"aaaa男2");
pstmt->setString(3,"aaaa!");
pstmt->setString(4,"123123");
pstmt->execute();

7,执行查询语句

sql::Statement *stmt;
sql::ResultSet *res;
std::string qry = "select * from user";
stmt = con->createStatement();
//选择使用的数据库的名字
stmt->execute("use cloud_disk");
res = stmt->executeQuery(qry);
while(res->next()){
std::cout << res->getInt(1);
std::cout << res->getString(2) << std::endl;
}

8,释放资源

  • 除了sql::mysql::MySQL_Driver *driver指针,都需要手动调用delete释放

    delete res;
    delete stmt;
    delete con;

c/c++ 学习互助QQ群:877684253

mysql connector c++ 1.1 API初步体验-LMLPHP

本人微信:xiaoshitou5854

05-11 17:23