First, make sure you have installed the mysql-connector-python library, if not installed, you can use the following command to install
pip install mysql-connector-python
Then, here is the content of the python script
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)
When you run this script, it will connect to the MySQL server, create a new user, and grant that user all privileges on the specified database.
Note: Please make sure you have sufficient permissions to create users and grant permissions, and be very careful when using this script, as it involves database security.