python鏈接mysql
阿新 • • 發佈:2017-05-08
org oot set Coding span port 小例子 use col
1.安裝MySQLdb
MySQLdb 是用於Python鏈接Mysql數據庫的接口,它實現了 Python 數據庫 API 規範 V2.0,基於 MySQL C API 上建立的。
下載地址:
http://sourceforge.net/projects/mysql-python/files/mysql-python/
我下載了1.2.3版本
2.代碼
1 #!/usr/bin/python 2 # -*- coding: UTF-8 -*- 3 import MySQLdb 4 # 打開數據庫連接 5 db = MySQLdb.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘‘, db=‘xxx‘, charset=‘utf8‘) 6 # 使用cursor()方法獲取操作遊標 7 cursor = db.cursor() 8 # 使用execute方法執行SQL語句 9 cursor.execute("SELECT VERSION()") 10 data = cursor.fetchone() 11 print "mysql版本%s" %data 12 # 關閉數據庫連接 13 db.close()
這是最基本的一個小例子
python鏈接mysql