ubantu安装mysql + redis数据库并使用C/C++操作数据库

2024-09-07 23:28

本文主要是介绍ubantu安装mysql + redis数据库并使用C/C++操作数据库,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

mysql

安装mysql

ubuntu 安装 MySql_ubuntu安装mysql-CSDN博客

Ubuntu 安装 MySQL 密码设置_ubuntu安装mysql后设置密码-CSDN博客

service mysql restart1

C/C++连接数据库

C/C++ 连接访问 MySQL数据库_c++ mysql-CSDN博客

ubuntu安装mysql的c++开发环境_ubuntu 搭建mysql c++开发环境-CSDN博客

安装C

sudo apt install libmysqlclient-dev

编译命令

g++ main.cpp -lmysqlclient -o main

#include<stdio.h>
#include<iostream>
#include<mysql/mysql.h>
using namespace std;int main(int argc,char* argv[]){MYSQL conn;int res;mysql_init(&conn);if(mysql_real_connect(&conn,"127.0.0.1","root","Yaoaolong111","testdb",0,NULL,CLIENT_FOUND_ROWS)){cout<<"connect success"<<endl;/*************select sql example start************************/string sql = string("select * from ").append("test_table");mysql_query(&conn,sql.c_str());//收集查询得到的信息MYSQL_RES *result = NULL;result = mysql_store_result(&conn);//得到查询到的数据条数int row_count = mysql_num_rows(result);cout<<"all data number: "<< row_count << endl;//得到字段的个数和字段的名字int field_count = mysql_num_fields(result);cout << "filed count: " <<field_count << endl;//得到所有字段名MYSQL_FIELD *field = NULL;for(int i=0;i<field_count;++i){field = mysql_fetch_field_direct(result,i);cout<<field->name<<"\t";}cout<< endl;MYSQL_ROW row = NULL;row = mysql_fetch_row(result);while(NULL != row){for(int i=0; i<field_count;++i){cout <<row[i]<<"\t";}cout<<endl;row = mysql_fetch_row(result);}mysql_free_result(result);mysql_close(&conn);}else{cout<<"connect failed!"<<endl;}return 0;
}

安装Connector/C++

sudo apt-get install libmysqlcppconn-dev

编译C++

g++ your_program.cpp -o your_program -lmysqlcppconn

// 代码示例
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <mysql_driver.h>int main() {try {// 创建驱动实例sql::mysql::MySQL_Driver *driver = sql::mysql::get_mysql_driver_instance();// 创建连接sql::Connection *con = driver->connect("tcp://127.0.0.1:3306", "root", "Yaoaolong111");// 连接到数据库con->setSchema("testdb");// 创建语句对象sql::Statement *stmt = con->createStatement();// 执行查询sql::ResultSet *res = stmt->executeQuery("SELECT * FROM test_table");// 处理结果集while (res->next()) {// 获取列数据int column1 = res->getInt("id");std::string column2 = res->getString("name");// 处理数据...std::cout << column1 << " " << column2 << std::endl;}// 清理delete res;delete stmt;delete con;} catch (sql::SQLException &e) {std::cerr << "# ERR: SQLException in " << __FILE__ << "(" << __FUNCTION__ << ") on line "<< __LINE__ << ", " << e.what() << std::endl;return 1;}return 0;
}

redis

安装redis

ubuntu安装redis_ubuntu下安装redis-CSDN博客

sudo apt install redis-server

配置redis

vim /etc/redis/redis.conf

protected-mode yes----->no 可以远程访问

bind 0.0.0.0 改ip

deamonize yes 表示使用守护进程方式执行

C/C++操作redis

安装hiredis——C语言

sudo apt install libhiredis-dev

代码示例

#include <stdio.h>
#include <stdlib.h>
#include <hiredis.h>int main(int argc, char **argv) {redisContext *c;redisReply *reply;c = redisConnect("127.0.0.1", 6379);if (c == NULL || c->err) {printf("Connection error: %s\n", c ? c->errstr : "Can't allocate redis context");return 1;}reply = redisCommand(c, "SET key value");if (reply == NULL || reply->type != REDIS_REPLY_STATUS) {printf("SET error: %s\n", reply ? reply->str : "Unknown error");freeReplyObject(reply);redisFree(c);return 1;}printf("SET command succeeded.\n");reply = redisCommand(c, "GET key");if (reply == NULL || reply->type != REDIS_REPLY_STRING) {printf("GET error: %s\n", reply ? reply->str : "Unknown error");freeReplyObject(reply);} else {printf("The value of 'key' is: %s\n", reply->str);}freeReplyObject(reply);redisFree(c);return 0;
}

安装redis-plus-plus——C++

# 网页连接
https://github.com/sewenew/redis-plus-plus# 如果想要进行clone,自己必须先配置自己的config
# 安装
git clone https://github.com/sewenew/redis-plus-plus.git
cd redis-plus-plus
mkdir build
cd build
cmake ..
make
make install
cd ..

代码示例

#include <sw/redis++/redis++.h>
#include <iostream>
using namespace std;
using namespace sw::redis;int main()
{try{// Create an Redis object, which is movable but NOT copyable.auto redis = Redis("tcp://127.0.0.1:6379");// ***** STRING commands *****redis.set("key", "val");auto val = redis.get("key"); // val is of type OptionalString. See 'API Reference' section for details.if (val){// Dereference val to get the returned value of std::string type.std::cout << *val << std::endl;} // else key doesn't exist.// ***** LIST commands *****// std::vector<std::string> to Redis LIST.std::vector<std::string> vec = {"a", "b", "c"};redis.rpush("list", vec.begin(), vec.end());// std::initializer_list to Redis LIST.redis.rpush("list", {"a", "b", "c"});// Redis LIST to std::vector<std::string>.vec.clear();redis.lrange("list", 0, -1, std::back_inserter(vec));// ***** HASH commands *****redis.hset("hash", "field", "val");// Another way to do the same job.redis.hset("hash", std::make_pair("field", "val"));// std::unordered_map<std::string, std::string> to Redis HASH.std::unordered_map<std::string, std::string> m = {{"field1", "val1"},{"field2", "val2"}};redis.hmset("hash", m.begin(), m.end());// Redis HASH to std::unordered_map<std::string, std::string>.m.clear();redis.hgetall("hash", std::inserter(m, m.begin()));// Get value only.// NOTE: since field might NOT exist, so we need to parse it to OptionalString.std::vector<OptionalString> vals;redis.hmget("hash", {"field1", "field2"}, std::back_inserter(vals));// ***** SET commands *****redis.sadd("set", "m1");// std::unordered_set<std::string> to Redis SET.std::unordered_set<std::string> set = {"m2", "m3"};redis.sadd("set", set.begin(), set.end());// std::initializer_list to Redis SET.redis.sadd("set", {"m2", "m3"});// Redis SET to std::unordered_set<std::string>.set.clear();redis.smembers("set", std::inserter(set, set.begin()));if (redis.sismember("set", "m1")){std::cout << "m1 exists" << std::endl;} // else NOT exist.// ***** SORTED SET commands *****redis.zadd("sorted_set", "m1", 1.3);// std::unordered_map<std::string, double> to Redis SORTED SET.std::unordered_map<std::string, double> scores = {{"m2", 2.3},{"m3", 4.5}};redis.zadd("sorted_set", scores.begin(), scores.end());// Redis SORTED SET to std::vector<std::pair<std::string, double>>.// NOTE: The return results of zrangebyscore are ordered, if you save the results// in to `std::unordered_map<std::string, double>`, you'll lose the order.std::vector<std::pair<std::string, double>> zset_result;redis.zrangebyscore("sorted_set",UnboundedInterval<double>{}, // (-inf, +inf)std::back_inserter(zset_result));// Only get member names:// pass an inserter of std::vector<std::string> type as output parameter.std::vector<std::string> without_score;redis.zrangebyscore("sorted_set",BoundedInterval<double>(1.5, 3.4, BoundType::CLOSED), // [1.5, 3.4]std::back_inserter(without_score));// Get both member names and scores:// pass an back_inserter of std::vector<std::pair<std::string, double>> as output parameter.std::vector<std::pair<std::string, double>> with_score;redis.zrangebyscore("sorted_set",BoundedInterval<double>(1.5, 3.4, BoundType::LEFT_OPEN), // (1.5, 3.4]std::back_inserter(with_score));// ***** SCRIPTING commands *****// Script returns a single element.auto num = redis.eval<long long>("return 1", {}, {});// Script returns an array of elements.std::vector<std::string> nums;redis.eval("return {ARGV[1], ARGV[2]}", {}, {"1", "2"}, std::back_inserter(nums));// mset with TTLauto mset_with_ttl_script = R"(local len = #KEYSif (len == 0 or len + 1 ~= #ARGV) then return 0 endlocal ttl = tonumber(ARGV[len + 1])if (not ttl or ttl <= 0) then return 0 endfor i = 1, len do redis.call("SET", KEYS[i], ARGV[i], "EX", ttl) endreturn 1)";// Set multiple key-value pairs with TTL of 60 seconds.auto keys = {"key1", "key2", "key3"};std::vector<std::string> args = {"val1", "val2", "val3", "60"};redis.eval<long long>(mset_with_ttl_script, keys.begin(), keys.end(), args.begin(), args.end());// ***** Pipeline *****// Create a pipeline.auto pipe = redis.pipeline();// Send mulitple commands and get all replies.auto pipe_replies = pipe.set("key", "value").get("key").rename("key", "new-key").rpush("list", {"a", "b", "c"}).lrange("list", 0, -1).exec();// Parse reply with reply type and index.auto set_cmd_result = pipe_replies.get<bool>(0);auto get_cmd_result = pipe_replies.get<OptionalString>(1);// rename command resultpipe_replies.get<void>(2);auto rpush_cmd_result = pipe_replies.get<long long>(3);std::vector<std::string> lrange_cmd_result;pipe_replies.get(4, back_inserter(lrange_cmd_result));// ***** Transaction *****// Create a transaction.auto tx = redis.transaction();// Run multiple commands in a transaction, and get all replies.auto tx_replies = tx.incr("num0").incr("num1").mget({"num0", "num1"}).exec();// Parse reply with reply type and index.auto incr_result0 = tx_replies.get<long long>(0);auto incr_result1 = tx_replies.get<long long>(1);std::vector<OptionalString> mget_cmd_result;tx_replies.get(2, back_inserter(mget_cmd_result));// ***** Generic Command Interface *****// There's no *Redis::client_getname* interface.// But you can use *Redis::command* to get the client name.val = redis.command<OptionalString>("client", "getname");if (val){std::cout << *val << std::endl;}// Same as above.auto getname_cmd_str = {"client", "getname"};val = redis.command<OptionalString>(getname_cmd_str.begin(), getname_cmd_str.end());// There's no *Redis::sort* interface.// But you can use *Redis::command* to send sort the list.std::vector<std::string> sorted_list;redis.command("sort", "list", "ALPHA", std::back_inserter(sorted_list));// Another *Redis::command* to do the same work.auto sort_cmd_str = {"sort", "list", "ALPHA"};redis.command(sort_cmd_str.begin(), sort_cmd_str.end(), std::back_inserter(sorted_list));// ***** Redis Cluster *****// Create a RedisCluster object, which is movable but NOT copyable.auto redis_cluster = RedisCluster("tcp://127.0.0.1:7000");// RedisCluster has similar interfaces as Redis.redis_cluster.set("key", "value");val = redis_cluster.get("key");if (val){std::cout << *val << std::endl;} // else key doesn't exist.// Keys with hash-tag.redis_cluster.set("key{tag}1", "val1");redis_cluster.set("key{tag}2", "val2");redis_cluster.set("key{tag}3", "val3");std::vector<OptionalString> hash_tag_res;redis_cluster.mget({"key{tag}1", "key{tag}2", "key{tag}3"},std::back_inserter(hash_tag_res));}catch (const Error &e){// Error handling.}
}

redis-plus-plus:Redis client written in C++ - GitCode,文档

这篇关于ubantu安装mysql + redis数据库并使用C/C++操作数据库的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1146463

相关文章

如何使用celery进行异步处理和定时任务(django)

《如何使用celery进行异步处理和定时任务(django)》文章介绍了Celery的基本概念、安装方法、如何使用Celery进行异步任务处理以及如何设置定时任务,通过Celery,可以在Web应用中... 目录一、celery的作用二、安装celery三、使用celery 异步执行任务四、使用celery

使用Python绘制蛇年春节祝福艺术图

《使用Python绘制蛇年春节祝福艺术图》:本文主要介绍如何使用Python的Matplotlib库绘制一幅富有创意的“蛇年有福”艺术图,这幅图结合了数字,蛇形,花朵等装饰,需要的可以参考下... 目录1. 绘图的基本概念2. 准备工作3. 实现代码解析3.1 设置绘图画布3.2 绘制数字“2025”3.3

Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单

《Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单》:本文主要介绍Springboot的ThreadPoolTaskScheduler线... 目录ThreadPoolTaskScheduler线程池实现15分钟不操作自动取消订单概要1,创建订单后

详谈redis跟数据库的数据同步问题

《详谈redis跟数据库的数据同步问题》文章讨论了在Redis和数据库数据一致性问题上的解决方案,主要比较了先更新Redis缓存再更新数据库和先更新数据库再更新Redis缓存两种方案,文章指出,删除R... 目录一、Redis 数据库数据一致性的解决方案1.1、更新Redis缓存、删除Redis缓存的区别二

oracle数据库索引失效的问题及解决

《oracle数据库索引失效的问题及解决》本文总结了在Oracle数据库中索引失效的一些常见场景,包括使用isnull、isnotnull、!=、、、函数处理、like前置%查询以及范围索引和等值索引... 目录oracle数据库索引失效问题场景环境索引失效情况及验证结论一结论二结论三结论四结论五总结ora

Redis与缓存解读

《Redis与缓存解读》文章介绍了Redis作为缓存层的优势和缺点,并分析了六种缓存更新策略,包括超时剔除、先删缓存再更新数据库、旁路缓存、先更新数据库再删缓存、先更新数据库再更新缓存、读写穿透和异步... 目录缓存缓存优缺点缓存更新策略超时剔除先删缓存再更新数据库旁路缓存(先更新数据库,再删缓存)先更新数

Jsoncpp的安装与使用方式

《Jsoncpp的安装与使用方式》JsonCpp是一个用于解析和生成JSON数据的C++库,它支持解析JSON文件或字符串到C++对象,以及将C++对象序列化回JSON格式,安装JsonCpp可以通过... 目录安装jsoncppJsoncpp的使用Value类构造函数检测保存的数据类型提取数据对json数

Redis事务与数据持久化方式

《Redis事务与数据持久化方式》该文档主要介绍了Redis事务和持久化机制,事务通过将多个命令打包执行,而持久化则通过快照(RDB)和追加式文件(AOF)两种方式将内存数据保存到磁盘,以防止数据丢失... 目录一、Redis 事务1.1 事务本质1.2 数据库事务与redis事务1.2.1 数据库事务1.

python使用watchdog实现文件资源监控

《python使用watchdog实现文件资源监控》watchdog支持跨平台文件资源监控,可以检测指定文件夹下文件及文件夹变动,下面我们来看看Python如何使用watchdog实现文件资源监控吧... python文件监控库watchdogs简介随着Python在各种应用领域中的广泛使用,其生态环境也

Python中构建终端应用界面利器Blessed模块的使用

《Python中构建终端应用界面利器Blessed模块的使用》Blessed库作为一个轻量级且功能强大的解决方案,开始在开发者中赢得口碑,今天,我们就一起来探索一下它是如何让终端UI开发变得轻松而高... 目录一、安装与配置:简单、快速、无障碍二、基本功能:从彩色文本到动态交互1. 显示基本内容2. 创建链