— Posted in 程式設計

Python 連接 MySQL 資料庫

#!/usr/bin/python
#-*- coding:utf-8 -*-

import MySQLdb

db = MySQLdb.connect(host=”資料庫位置”, user=”使用者名稱”, passwd=”密碼”, db=”最初要連到的資料庫”,charset=”utf8″)
cursor = db.cursor()

#== 語法  ==============================

last = datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)
sql=”delete from DeptTelCost where rpt_Date='” + last.strftime(‘%Y-%m’) + “‘;”
cursor.execute(sql)
try:
db.commit()
except:
db.rollback()

#===============================================

cursor.execute(“SELECT CODE,Descr FROM Dept WHERE Code IN (‘AAA1′,’A000′,’018S’);”)
row=cursor.fetchall()
for record in row:

 

#== 關閉資料庫 ============
db.close()
workbook.close()