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

相关文章

Python正则表达式匹配和替换的操作指南

《Python正则表达式匹配和替换的操作指南》正则表达式是处理文本的强大工具,Python通过re模块提供了完整的正则表达式功能,本文将通过代码示例详细介绍Python中的正则匹配和替换操作,需要的朋... 目录基础语法导入re模块基本元字符常用匹配方法1. re.match() - 从字符串开头匹配2.

C++右移运算符的一个小坑及解决

《C++右移运算符的一个小坑及解决》文章指出右移运算符处理负数时左侧补1导致死循环,与除法行为不同,强调需注意补码机制以正确统计二进制1的个数... 目录我遇到了这么一个www.chinasem.cn函数由此可以看到也很好理解总结我遇到了这么一个函数template<typename T>unsigned

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

MySQL的JDBC编程详解

《MySQL的JDBC编程详解》:本文主要介绍MySQL的JDBC编程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言一、前置知识1. 引入依赖2. 认识 url二、JDBC 操作流程1. JDBC 的写操作2. JDBC 的读操作总结前言本文介绍了mysq

java.sql.SQLTransientConnectionException连接超时异常原因及解决方案

《java.sql.SQLTransientConnectionException连接超时异常原因及解决方案》:本文主要介绍java.sql.SQLTransientConnectionExcep... 目录一、引言二、异常信息分析三、可能的原因3.1 连接池配置不合理3.2 数据库负载过高3.3 连接泄漏

Redis 的 SUBSCRIBE命令详解

《Redis的SUBSCRIBE命令详解》Redis的SUBSCRIBE命令用于订阅一个或多个频道,以便接收发送到这些频道的消息,本文给大家介绍Redis的SUBSCRIBE命令,感兴趣的朋友跟随... 目录基本语法工作原理示例消息格式相关命令python 示例Redis 的 SUBSCRIBE 命令用于订

Linux下MySQL数据库定时备份脚本与Crontab配置教学

《Linux下MySQL数据库定时备份脚本与Crontab配置教学》在生产环境中,数据库是核心资产之一,定期备份数据库可以有效防止意外数据丢失,本文将分享一份MySQL定时备份脚本,并讲解如何通过cr... 目录备份脚本详解脚本功能说明授权与可执行权限使用 Crontab 定时执行编辑 Crontab添加定

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC