[Python] PyMySQL

基礎用法

import pymysql

connection = pymysql.connect(
  host='localhost', 
  port=3306, 
  user='root', 
  passwd='******', 
  db='db', 
  charset='utf8'
)

#---
cursor = connection.cursor()

def execute(sql):
  try:
    cursor.execute(sql)
  except Exception as ex:
    connection.rollback()
    return ex
  else:
    connection.commit() 
    return True

sql = f"...;"
execute(sql)

connection.close()

""" Or
with connection:
  with connection.cursor() as cursor:
    sql = '''...;'''
    cursor.execute(sql)

  # Connection is not autocommit by default.
  # So you must commit to save your changes.
  connection.commit()
"""

取得查詢結果

cursor.fetchone() / cursor.fetchall():pop 一筆/全部 結果

Last Updated on 2023/08/16 by A1go

目錄
Bitnami