mysql connector c++ 1.1 API初步体验
程序员文章站
2022-07-01 23:32:34
mysql connector c++ 1.1 API初步体验 1,常用的头文件 2,创建连接 3,选择要使用的database的名字 4,设置连接的属性,例子是设置连接的字符集 5,判断连接是否建立成功 7,执行查询语句 c++ sql::Statement stmt; sql::ResultSe ......
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
本人微信:xiaoshitou5854
下一篇: 利用js代码自动删除稿件的普通弹幕