以下是一个示例的分库分表的shell脚本,其中库名从00开始,16个库,表名从0000开始,每个库128张表,共2048张表。该脚本根据输入的数据进行hash取模操作,将数据写入对应的库和表中。

#!/bin/bash

# 输入数据
data=$1

# 计算hash值
hash=$(echo -n $data | md5sum | awk '{print $1}')
hash_dec=$((16#${hash}))
hash_mod=$((hash_dec % 2048))

# 计算库名和表名
db_index=$((hash_mod / 128))
table_index=$((hash_mod % 128))
db_name=$(printf "%02d" $db_index)
table_name=$(printf "%04d" $table_index)

# 连接数据库并插入数据
mysql -h localhost -u root -p -e "USE db_${db_name}; INSERT INTO table_${table_name} (data) VALUES ('$data');"

echo "数据 $data 已写入 db_${db_name}.table_${table_name}"

使用示例:

$ sh hash_mod.sh "test data"

该脚本将输入的数据进行hash取模操作,计算出对应的库名和表名,并使用mysql连接数据库将数据插入对应的库和表中

shell脚本mysql分库分表库名从00开始16个库表名从0000开始每个库128张表共2048张表。hash取模数据写入示例

原文地址: https://www.cveoy.top/t/topic/hOQg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录