OTL 库和soci库 链接数据,分别给个demo,我参考下哪个简单好用
时间: 2024-02-19 19:57:37 浏览: 29
以下是OTL库和Soci库链接MySQL数据库的简单示例,供您参考。
OTL库链接MySQL数据库的示例代码:
```c++
#include <iostream>
#include <string>
#include <vector>
#include <otlv4.h>
int main()
{
try
{
std::string db_user = "your_user_name";
std::string db_password = "your_password";
std::string db_name = "your_database_name";
std::string db_host = "your_host_name";
int db_port = 3306;
otl_connect db;
db.rlogon("user=" + db_user + ";password=" + db_password + ";database=" + db_name + ";host=" + db_host + ";port=" + std::to_string(db_port));
otl_stream os;
os.open(1, "SELECT * FROM your_table", db);
std::vector<std::string> result;
while (!os.eof())
{
std::string value;
os >> value;
result.push_back(value);
}
os.close();
db.logoff();
for (auto& value : result)
{
std::cout << value << std::endl;
}
}
catch (otl_exception& e)
{
std::cerr << e.msg << std::endl;
}
return 0;
}
```
Soci库链接MySQL数据库的示例代码:
```c++
#include <iostream>
#include <string>
#include <vector>
#include <soci/soci.h>
#include <soci/mysql/soci-mysql.h>
int main()
{
try
{
std::string db_user = "your_user_name";
std::string db_password = "your_password";
std::string db_name = "your_database_name";
std::string db_host = "your_host_name";
int db_port = 3306;
soci::session db(soci::mysql, "user=" + db_user + " password=" + db_password + " dbname=" + db_name + " host=" + db_host + " port=" + std::to_string(db_port));
std::vector<std::string> result;
soci::rowset<soci::row> rs = (db.prepare << "SELECT * FROM your_table");
for (auto it = rs.begin(); it != rs.end(); ++it)
{
soci::row const& row = *it;
std::string value;
row.get<std::string>(0, value);
result.push_back(value);
}
for (auto& value : result)
{
std::cout << value << std::endl;
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
```
这两个库都有简单易用的API,选择哪一个更好需要根据个人需求和项目要求来决定。