使用Python配置MySQL数据库:自动化用户授权工具

在这里插入图片描述

首先,确保你已经安装了mysql-connector-python库,如果还没有安装,可以使用以下命令进行安装

pip install mysql-connector-python

然后,这是Python脚本的内容

import mysql.connector
from mysql.connector import Error

def create_user(host_name, user_name, user_password, new_user_name, new_user_password, db_name):
    # 创建数据库连接
    connection = mysql.connector.connect(host=host_name, 
                                         user=user_name, 
                                         passwd=user_password)
    cursor = connection.cursor()
    try:
        # 创建新用户
        cursor.execute(f"CREATE USER '{new_user_name}'@'localhost' IDENTIFIED BY '{new_user_password}';")
        
        # 授予新用户对指定数据库的所有权限
        cursor.execute(f"GRANT ALL PRIVILEGES ON {db_name} . * TO '{new_user_name}'@'localhost';")
        
        # 提交修改
        connection.commit()
        
        print(f"User {new_user_name} created successfully.")
    except Error as e:
        print(f"Error: '{e}'")
    finally:
        # 关闭数据库连接
        cursor.close()
        connection.close()

# 使用你的MySQL服务器详细信息替换下面的值
host_name = "localhost"
user_name = "root"
user_password = "rootpassword"

# 创建的新用户的用户名和密码
new_user_name = "newuser"
new_user_password = "newpassword"

# 要授予权限的数据库
db_name = "mydatabase"

create_user(host_name, user_name, user_password, new_user_name, new_user_password, db_name)

当你运行这个脚本时,它将连接到MySQL服务器,创建一个新用户,并授予该用户对指定数据库的所有权限。

注意:请确保你有足够的权限来创建用户和授予权限,并且使用这个脚本时要非常小心,因为它涉及到数据库安全。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

苏呆仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值