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

相关文章

shell编程之函数与数组的使用详解

《shell编程之函数与数组的使用详解》:本文主要介绍shell编程之函数与数组的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录shell函数函数的用法俩个数求和系统资源监控并报警函数函数变量的作用范围函数的参数递归函数shell数组获取数组的长度读取某下的

使用Python开发一个带EPUB转换功能的Markdown编辑器

《使用Python开发一个带EPUB转换功能的Markdown编辑器》Markdown因其简单易用和强大的格式支持,成为了写作者、开发者及内容创作者的首选格式,本文将通过Python开发一个Markd... 目录应用概览代码结构与核心组件1. 初始化与布局 (__init__)2. 工具栏 (setup_t

如何在pycharm安装torch包

《如何在pycharm安装torch包》:本文主要介绍如何在pycharm安装torch包方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录在pycharm安装torch包适http://www.chinasem.cn配于我电脑的指令为适用的torch包为总结在p

在PyCharm中安装PyTorch、torchvision和OpenCV详解

《在PyCharm中安装PyTorch、torchvision和OpenCV详解》:本文主要介绍在PyCharm中安装PyTorch、torchvision和OpenCV方式,具有很好的参考价值,... 目录PyCharm安装PyTorch、torchvision和OpenCV安装python安装PyTor

Python虚拟环境终极(含PyCharm的使用教程)

《Python虚拟环境终极(含PyCharm的使用教程)》:本文主要介绍Python虚拟环境终极(含PyCharm的使用教程),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录一、为什么需要虚拟环境?二、虚拟环境创建方式对比三、命令行创建虚拟环境(venv)3.1 基础命令3

Python Transformer 库安装配置及使用方法

《PythonTransformer库安装配置及使用方法》HuggingFaceTransformers是自然语言处理(NLP)领域最流行的开源库之一,支持基于Transformer架构的预训练模... 目录python 中的 Transformer 库及使用方法一、库的概述二、安装与配置三、基础使用:Pi

Python 中的 with open文件操作的最佳实践

《Python中的withopen文件操作的最佳实践》在Python中,withopen()提供了一个简洁而安全的方式来处理文件操作,它不仅能确保文件在操作完成后自动关闭,还能处理文件操作中的异... 目录什么是 with open()?为什么使用 with open()?使用 with open() 进行

关于pandas的read_csv方法使用解读

《关于pandas的read_csv方法使用解读》:本文主要介绍关于pandas的read_csv方法使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录pandas的read_csv方法解读read_csv中的参数基本参数通用解析参数空值处理相关参数时间处理相关

使用Node.js制作图片上传服务的详细教程

《使用Node.js制作图片上传服务的详细教程》在现代Web应用开发中,图片上传是一项常见且重要的功能,借助Node.js强大的生态系统,我们可以轻松搭建高效的图片上传服务,本文将深入探讨如何使用No... 目录准备工作搭建 Express 服务器配置 multer 进行图片上传处理图片上传请求完整代码示例

MySQL 分区与分库分表策略应用小结

《MySQL分区与分库分表策略应用小结》在大数据量、复杂查询和高并发的应用场景下,单一数据库往往难以满足性能和扩展性的要求,本文将详细介绍这两种策略的基本概念、实现方法及优缺点,并通过实际案例展示如... 目录mysql 分区与分库分表策略1. 数据库水平拆分的背景2. MySQL 分区策略2.1 分区概念