python 建立mysql資料庫腳(執行sql)指令碼程式碼

二月雪發表於2024-12-03

安裝依賴庫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)

相關文章