安装 Python MySQL 驱动(mysql-connector-python、MySQL-python)
生活随笔
收集整理的這篇文章主要介紹了
安装 Python MySQL 驱动(mysql-connector-python、MySQL-python)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1. 安裝
由于 MySQL 服務(wù)器以獨(dú)立的進(jìn)程運(yùn)行,并通過網(wǎng)絡(luò)對(duì)外服務(wù),所以,需要支持 Python 的MySQL 驅(qū)動(dòng)來連接到 MySQL 服務(wù)器。
目前,有兩個(gè)MySQL驅(qū)動(dòng):
-
mysql-connector-python:是MySQL官方的純Python驅(qū)動(dòng);
-
MySQL-python:是封裝了MySQL C驅(qū)動(dòng)的Python驅(qū)動(dòng)。
可以把兩個(gè)都裝上,使用的時(shí)候再?zèng)Q定用哪個(gè):
$ easy_install mysql-connector-python
$ easy_install MySQL-python
2. 示例
我們以 mysql-connector-python 為例,演示如何連接到 MySQL 服務(wù)器的 test 數(shù)據(jù)庫(kù):
import mysql.connectorconn = mysql.connector.connect(user='root', password='password', database='test', use_unicode=True)
cursor = conn.cursor()cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')cursor.execute('insert into user (id, name) values (%s, %s)', ['1', 'Michael'])
>>> cursor.rowcount
1>>> conn.commit()
>>> cursor.close()>>> cursor = conn.cursor()
>>> cursor.execute('select * from user where id = %s', ('1',))
>>> values = cursor.fetchall()
>>> values
[(u'1', u'Michael')]>>> cursor.close()
True
>>> conn.close()
總結(jié)
以上是生活随笔為你收集整理的安装 Python MySQL 驱动(mysql-connector-python、MySQL-python)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《题山石榴花》第四句是什么
- 下一篇: 乌镇古镇门票多少钱