python 创建mysql数据库脚(执行sql)脚本代码
安装依赖库mysql-connector-python
pip install mysql-connector-python
执行创建数据库的sql脚本代码
import mysql.connector
from mysql.connector import Error
def create_database(db_name, host_name="192.168.0.33", user_name="root", user_password="SHUfu1209"):
connection = None
cursor = None
try:
# 创建与MySQL服务器的连接
connection = mysql.connector.connect(
host=host_name,
user=user_name,
passwd=user_password
)
print("MySQL Database connection successful")
# 获取游标对象
cursor = connection.cursor()
# 执行SQL命令创建数据库
create_db_query = f"CREATE DATABASE {db_name}"
cursor.execute(create_db_query)
print(f"Database '{db_name}' created successfully")
except Error as e:
print(f"The error '{e}' occurred")
finally:
if connection.is_connected():
connection.close()
if cursor:
cursor.close()
print("MySQL connection is closed")
if __name__ == '__main__':
# 使用你的MySQL服务器信息替换这些值
host = "192.168.0.2"
user = "root"
password = "123456"
database_name = "database"
create_database(host, user, password, database_name)