在python中:
1. 串連:
Python代碼
import mysql.connector cnx = mysql.connector.connect(user='scott', password='tiger', host='127.0.0.1', database='employees') cnx.close()
2. 查詢:
Python代碼
import datetime import mysql.connector cnx = mysql.connector.connect(user='scott', database='employees') cursor = cnx.cursor() query = ("SELECT first_name, last_name, hire_date FROM employees " "WHERE hire_date BETWEEN %s AND %s") hire_start = datetime.date(1999, 1, 1) hire_end = datetime.date(1999, 12, 31) cursor.execute(query, (hire_start, hire_end)) for (first_name, last_name, hire_date) in cursor: print("{}, {} was hired on {:%d %b %Y}".format( last_name, first_name, hire_date)) cursor.close() cnx.close()
3. 輸出到檔案(使用當前日期做檔案名稱)
Python代碼
import time filename = 'page_list_'+str(time.strftime("%Y%m%d"))+'.txt' output = open(filename,'w') output.write(str(page_title).lstrip('(b\'').rstrip('\',)')+"\n") output.close()
這裡page_title是上面從資料庫中檢索出來的欄位名。因為輸出都是(b'pagename')的格式,所以又做了一些處理,刪除了多餘的字元。
這樣,檢索出的內容就可以直接儲存到以日期為名字的檔案中了。