c++操作数据库(增删改查)------otl库----c++

文章目录

  • 一, insert 插入数据库
  • 二, select 查询
    • select 写法一
    • select 写法二
  • 三, update 修改
  • 四, delete 删除

包含头文件:#include <otl/otlv4.h>

一, insert 插入数据库

#include <iostream>
#include <otl/otlv4.h> // 请确保正确包含 OTL 头文件void insertDataIntoTable(const std::string& server, const std::string& database, const std::string& uid, const std::string& pwd, int field1, const std::string& field2_str)
{otl_connect db; // 创建 otl_connect 对象,并连接到数据库try{// 连接数据库db.rlogon(("Driver={SQL Server};Server=" + server + ";Port:1433;Database=" + database + ";UID=" + uid + ";PWD=" + pwd).c_str());// 打开插入流otl_stream insert_stream;insert_stream.open(256, "insert into data_name.dba.Table_name (字段1, 时间字段2,时间字段3) values (:f1<int>, :f2<timestamp>,GETDATE())", db);// 准备变量值otl_value<int> a(field1);otl_datetime b;b.from<otl_datetime::Timestamp>(field2_str.c_str()); // 将字符串转化为时间格式// 将数据写入otl_write_row(insert_stream, a, b);insert_stream.flush();insert_stream.close();}catch (otl_exception& e){std::cout << "insert error" << std::endl;LOG_F(ERROR, "insert error, \nsql:%s \nmessage:%s \n state:%s", e.stm_text, e.msg, e.sqlstate);}catch (const std::exception& p){LOG_F(ERROR, "%s", p.what());}// 断开数据库连接db.logoff();
}int main()
{// 调用函数插入数据insertDataIntoTable("****", "***", "sa", "****", 4, "2023-11-30 12:34:56");return 0;
}

二, select 查询

select 写法一

#include <iostream>
#include <otl/otlv4.h> // 请确保正确包含 OTL 头文件bool fetchDataFromDatabase(const std::string& server, const std::string& database, const std::string& uid, const std::string& pwd, std::map<std::string, std::string>& adcd2adnm)
{otl_connect db; // 创建 otl_connect 对象,并连接到数据库try{// 连接数据库db.rlogon(("Driver={SQL Server};Server=" + server + ";Port:1433;Database=" + database + ";UID=" + uid + ";PWD=" + pwd).c_str());// 查询 WarningObject 表数据otl_stream warningObjectStream;warningObjectStream.open(512, "SELECT NAME, WARNINGGRADEID, BEGINTIME FROM 库名", db);for (auto& warn : warningObjectStream){otl_value<std::string> name;otl_value<int> warninggradeid;otl_value<otl_datetime> begintime;otl_read_row(warn, name, warninggradeid, begintime);std::string nameStr = name.v;int warninggradeidValue = warninggradeid.v;std::string begintimeStr = otl_datetime_to_string(begintime.v);  // 将otl_datetime类型转为string类型}warningObjectStream.close(); // 关闭查询流// 断开数据库连接db.logoff();return true;}catch (otl_exception& e){std::cout << "select error" << std::endl;LOG_F(ERROR, "select error, \n sql:%s \nmessage:%s \n state:%s", e.stm_text, e.msg, e.sqlstate);db.logoff();return false;}catch (const std::exception& p){LOG_F(ERROR, "%s", p.what());db.logoff();return false;}
}int main()
{std::map<std::string, std::string> adcd2adnm;// 调用函数获取数据if (fetchDataFromDatabase("****", "***", "sa", "****", adcd2adnm)){// 已成功获取}return 0;
}

select 写法二

#include <iostream>
#include <otl/otlv4.h> // Make sure to include the correct OTL headervoid fetchDataAndPopulateMap(double fieldValue1, double fieldValue2, std::map<int, std::map<int, int>>& lng_lat_pid)
{otl_connect db; // 创建otl_connect对象并连接到数据库try{otl_stream query_stream;db.rlogon("Driver={SQL Server};Server=****;Port:1433;Database=***;UID=sa;PWD=****");query_stream.open(256, "select 查询字段 form 库名.dbo.表名 where 表字段1=:f1<float> and 表字段2=:f2<float>", db, otl_implicit_select);// Bind the first input parameterquery_stream << fieldValue1;// Bind the second input parameterquery_stream << fieldValue2;otl_value<int> pid;otl_value<double> lat;otl_value<double> lon;while (!query_stream.eof()){otl_read_row(query_stream, pid, lat, lon);int x = std::round(lat.v * 1e4);int y = std::round(lon.v * 1e4);lng_lat_pid[x][y] = pid.v;}query_stream.close();}catch (otl_exception& e){std::cout << "select error" << std::endl;LOG_F(ERROR, "select error, \n sql:%s \nmessage:%s \n state:%s", e.stm_text, e.msg, e.sqlstate);}catch (const std::exception& p){LOG_F(ERROR, "%s", p.what());}db.logoff();
}int main()
{std::map<int, std::map<int, int>> lng_lat_pid;// 调用函数以获取数据并填充地图fetchDataAndPopulateMap(db, 10.0, lng_lat_pid);return 0;
}

三, update 修改


#include <iostream>
#include <otl/otlv4.h> bool updateWarnRecord(const std::string& dbConnectionString)
{otl_connect db;  // Database connection objecttry{// Connect to the database using the provided connection stringdb.rlogon(dbConnectionString.c_str());std::string update_sql = "UPDATE WarnRecord SET WarnETM =:f1<timestamp>, StatusID = 30 WHERE WarnID > 100;";otl_value<otl_datetime> wetm = "YYYY-MM-DD";otl_stream update_query;// Execute the update operationupdate_query.open(512, update_sql.c_str(), db);update_query << wetm;update_query.flush();update_query.close();db.logoff(); // Disconnect from the databasereturn true;}catch (otl_exception& ex){// Handle exceptionsstd::cout << "OTL Exception: " << ex.msg << std::endl;std::cout << "Oracle code: " << ex.code << std::endl;std::cout << "Oracle message: " << ex.sqlstate << std::endl;db.logoff(); // Disconnect from the databasereturn false;}
}int main()
{std::string dbConnectionString = "Replace with your database connection string";// Call the function to update the WarnRecordbool success = updateWarnRecord(dbConnectionString);if (success)std::cout << "Update successful." << std::endl;elsestd::cout << "Update failed." << std::endl;return 0;
}

四, delete 删除

#include <iostream>
#include <otl/otlv4.h> // Make sure to include the correct OTL headerbool deleteRecords(const std::string& dbConnectionString)
{otl_connect db;  // Database connection objecttry{// Connect to the database using the provided connection stringdb.rlogon(dbConnectionString.c_str());std::string delete_sql = "DELETE FROM Warn WHERE ADCD > 10";otl_stream delete_query;// Execute the delete operationdelete_query.open(128, delete_sql.c_str(), db);delete_query.flush();delete_query.close();db.logoff(); // Disconnect from the databasereturn true;}catch (otl_exception& ex){// Handle exceptionsstd::cout << "OTL Exception: " << ex.msg << std::endl;std::cout << "Oracle code: " << ex.code << std::endl;std::cout << "Oracle message: " << ex.sqlstate << std::endl;db.logoff(); // Disconnect from the databasereturn false;}
}int main()
{std::string dbConnectionString = "Replace with your database connection string";// Call the function to delete recordsbool success = deleteRecords(dbConnectionString);if (success)std::cout << "Deletion successful." << std::endl;elsestd::cout << "Deletion failed." << std::endl;return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/199808.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

回溯算法题型分类

题型一&#xff1a;排列、组合、子集相关问题 提示&#xff1a;这部分练习可以帮助我们熟悉「回溯算法」的一些概念和通用的解题思路。解题的步骤是&#xff1a;先画图&#xff0c;再编码。去思考可以剪枝的条件&#xff0c; 为什么有的时候用 used 数组&#xff0c;有的时候设…

前后端接口设计规范

设计规范原则 1. 前端应只关注渲染逻辑&#xff0c;而不应该关注数据的处理逻辑。接口返回的数据应该是能够直接展示在界面上的。 2. 一个功能应避免多个接口嵌套调用获取数据&#xff0c;后台应该处理好一次性返回。 3. 响应格式应该是JSON&#xff0c;而且应避免多级JSON的出…

hbase thrift2 jar包冲突导致启动失败问题排查记录

1、启动命令 ${HBASE_HOME}/bin/hbase-daemon.sh start thrift2 2、异常情况 hbase-root-thrift2-hdfs-test07.yingzi.com.out异常日志&#xff1a; Exception in thread "main" java.lang.AbstractMethodError: org.apache.hadoop.metrics2.sink.timeline.Hadoo…

3分钟在CentOS 7上离线安装Docker

在CentOS 7上离线安装Docker的详细步骤如下&#xff1a; 环境检查和准备 检查内核版本&#xff1a;Docker要求系统为64位且内核版本至少为3.10。使用命令uname -r查看内核版本。 检查CentOS版本&#xff1a;通过命令cat /etc/redhat-release查看版本信息。 更新yum包&#xff0…

java中强引用、软引用、弱引用、虚引用的区别是什么?

Java中的引用类型主要分为强引用、软引用、弱引用和虚引用&#xff0c;它们之间的区别主要体现在垃圾回收的行为上。 强引用&#xff08;Strong Reference&#xff09;&#xff1a;这是使用最普遍和默认的引用类型。如果一个对象具有强引用&#xff0c;那么垃圾回收器就永远不会…

Nginx(十二) gzip gzip_static sendfile directio aio 组合使用测试(2)

测试10&#xff1a;开启gzip、sendfile、aio、directio1m&#xff0c;关闭gzip_static&#xff0c;请求/index.js {"time_iso8601":"2023-11-30T17:20:5508:00","request_uri":"/index.js","status":"200","…

【Java Web学习笔记】4 - DOM文档对象模型

项目代码 https://github.com/yinhai1114/JavaWeb_LearningCode/tree/main/javascript 零、在线文档 JavaScript HTML DOM 一、HTML DOM基本介绍 1. DOM全称是Document Object Model文档对象模型 文档<---映射--->对象 2.就是把文档中的标签&#xff0c;属性&#xf…

WebSocket入门介绍及编程实战

HTTP的限制 全双工和半双工&#xff1a; 全双工&#xff1a;全双工&#xff08;Full Duplex&#xff09;是允许数据在两个方向上同时传输。 半双工&#xff1a;半双工&#xff08;Half Duplex&#xff09;是允许数据在两个方向上传输&#xff0c;但是同一个时间段内只允许一个…

【2】基于多设计模式下的同步异步日志系统-设计模式

6. 相关技术知识补充 6.1 不定参函数 在初学C语⾔的时候&#xff0c;我们都⽤过printf函数进⾏打印。其中printf函数就是⼀个不定参函数&#xff0c;在函数内部可以根据格式化字符串中格式化字符分别获取不同的参数进⾏数据的格式化。 ⽽这种不定参函数在实际的使⽤中也⾮常…

二十三种设计模式全面解析-解放组件间的通信束缚:深入探讨中介者模式的高级应用和进阶技巧

在软件开发中&#xff0c;组件之间的通信往往是不可避免的。然而&#xff0c;随着系统规模的增大和组件之间的相互依赖关系复杂化&#xff0c;直接的组件间通信往往会导致代码耦合度过高、可维护性下降等问题。为了解决这些问题&#xff0c;中介者模式应运而生。中介者模式通过…

解决 引element-plus依赖时的core-js报错

参考资料&#xff1a; https://blog.csdn.net/weixin_42164539/article/details/123388542 本人正在重构两年前搭建到一半的博客网站&#xff0c;相关依赖都很陈旧&#xff0c;用到了 npm-check-updates 检测项目可升级依赖&#xff1a; 补依赖过程始中报错 解决方案&#xf…

linux 内核同步互斥技术之信号量

信号量 信号量允许多个进程同时进入临界区&#xff0c;大多数情况下只允许一个进程进入临界区&#xff0c;把信号量的计数值设置为 1&#xff0c;即二值信号量&#xff0c;这种信号量称为互斥信号量。可允许多个锁持有者。 和自旋锁相比&#xff0c;信号量适合保护比较长的临界…

Java-宋红康-(P133-P134)-多线程创建方式(Thread and Runnable)

b站视频 133-多线程-线程创建方式1&#xff1a;继承Thread类_哔哩哔哩_bilibili 目录 3.1 继承Thread 3.1.1 继承Thread类方式 3.1.2 线程的执行流程 3.1.3 线程内存图 3.1.4 run()方法和start()方法 3.1.5 线程名字的设置和获取 3.1.6 获取运行main方法线程的名字 3.…

Linux进程间通信之共享内存

&#x1f4df;作者主页&#xff1a;慢热的陕西人 &#x1f334;专栏链接&#xff1a;Linux &#x1f4e3;欢迎各位大佬&#x1f44d;点赞&#x1f525;关注&#x1f693;收藏&#xff0c;&#x1f349;留言 本博客主要内容讲解共享内存原理和相关接口的介绍&#xff0c;以及一个…

更换cmd下默认选择Python解释器

问题 我的电脑里有多个Python解释器&#xff0c;一个是自己下载的python37&#xff0c;版本是3.7.0&#xff0c;一个是anaconda的base环境&#xff0c;版本是3.7.4&#xff0c;还有虚拟环境里的python解释器。 最近发现&#xff0c;在cmd下输入python&#xff0c;使用的是anac…

肺是人体的第一道防线,流感频发季节,最有效的养肺方法你得知道!

肺脏是人体的第一道防线&#xff0c;牵动着整个呼吸道的健康&#xff0c;一旦肺脏受损&#xff0c;易引发咳嗽、气喘甚至肺炎。在流感、呼吸道疾病高发的冬季&#xff0c;如何呵护肺脏&#xff0c;保持身体健康&#xff1f; 全民养肺&#xff0c;刻不容缓 养肺不仅仅是中老年朋…

深入浅出之中央空调体系架构及楼宇自控系统

一、关于建筑节能 1、建筑能耗 在中国&#xff0c;建筑能耗占社会总能耗45.5%。来源&#xff1a;《中国建筑能耗研究报告&#xff08;2022&#xff09;》 2、空调、采暖、照明占比最高 建筑节能是指在保证、提高建筑舒适性和生活质量的条件下&#xff0c;在建筑物使用的全过…

12.5 作业

1&#xff0c; 以下是一个简单的比喻&#xff0c;将多态概念与生活中的实际情况相联系&#xff1a; 比喻&#xff1a;动物园的讲解员和动物表演 想象一下你去了一家动物园&#xff0c;看到了许多不同种类的动物&#xff0c;如狮子、大象、猴子等。现在&#xff0c;动物园里有…

RocketMQTemplate 发送消息的高级用法

Apache RocketMQ 是一款强大的分布式消息中间件&#xff0c;与 Spring Boot 集成后&#xff0c;通过 RocketMQTemplate 可以实现在应用程序中方便地发送消息。在本文中&#xff0c;我们将深入探讨 RocketMQTemplate 的一些高级用法&#xff0c;以提供更灵活的消息发送和控制。 …

7天快速学习计算机基础必考八股文day02:操作系统

day02操作系统目录一览图 请简述对进程的理解——操作系统的进程详解请简述同步与异步的区别——进程状态模型详解请简述进程和线程的区别——操作系统线程详解请简述什么是操作系统的内核态——用户态与内核态详解IO密集型任务部署需要注意什么——程序运行类型分析协程是什么…