python獲取、修改mysql資料庫欄位屬性

AisaMaral發表於2024-04-08
import pymysql as sql

conn = sql.connect(
    host='localhost',
    user='root',
    password='20240108',
    database='usr'
)
table = 'tc2'
cur = conn.cursor()
try:
    cur.execute(f"SHOW COLUMNS FROM {table}")
    columns = cur.fetchall()
    print(columns)
    cols = [cl[0] for cl in columns]
    print(cols)
    for sr in cols:
        sq = f'ALTER TABLE {table} MODIFY COLUMN ' + sr + ' TEXT;'
        try:
            cur.execute(sq)
        except sql.IntegrityError:
            print(sq+'has an error')
except sql.OperationalError:
    print(sql.OperationalError)

相關文章