PyMySQL in Django

使用PyMySQL操作mysql數(shù)據(jù)庫

適用環(huán)境

python版本 >=2.6或3.3

mysql版本>=4.1

安裝

可以使用pip安裝也可以手動下載安裝。

使用pip安裝,在命令行執(zhí)行如下命令:

1pipinstallPyMySQL

手動安裝,請先下載。下載地址:https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X

其中的X.X是版本(目前可以獲取的最新版本是0.6.6)。

下載后解壓壓縮包。在命令行中進入解壓后的目錄,執(zhí)行如下的指令:

1pythonsetup.pyinstall

建議使用pip安裝。

使用示例

連接數(shù)據(jù)庫如下:

importpymysql.cursors

# Connect to the database

connection=pymysql.connect(host='127.0.0.1',

port=3306,

user='root',

password='zhyea.com',

db='employees',

charset='utf8mb4',

cursorclass=pymysql.cursors.DictCursor)

也可以使用字典進行連接參數(shù)的管理,我覺得這樣子更優(yōu)雅一些:

importpymysql.cursors

config={

'host':'127.0.0.1',

'port':3306,

'user':'root',

'password':'zhyea.com',

'db':'employees',

'charset':'utf8mb4',

'cursorclass':pymysql.cursors.DictCursor,

}

# Connect to the database

connection=pymysql.connect(**config)

插入數(shù)據(jù):

執(zhí)行sql語句前需要獲取cursor,因為配置默認(rèn)自動提交,故在執(zhí)行sql語句后需要主動commit,最后不要忘記關(guān)閉連接:

fromdatetimeimportdate,datetime,timedelta

importpymysql.cursors

#連接配置信息

config={

'host':'127.0.0.1',

'port':3306,

'user':'root',

'password':'zhyea.com',

'db':'employees',

'charset':'utf8mb4',

'cursorclass':pymysql.cursors.DictCursor,

}

# 創(chuàng)建連接

connection=pymysql.connect(**config)

# 獲取明天的時間

tomorrow=datetime.now().date()+timedelta(days=1)

# 執(zhí)行sql語句

try:

withconnection.cursor()ascursor:

# 執(zhí)行sql語句,插入記錄

sql='INSERT INTO employees (first_name, last_name, hire_date, gender, birth_date) VALUES (%s, %s, %s, %s, %s)'

cursor.execute(sql,('Robin','Zhyea',tomorrow,'M',date(1989,6,14)));

# 沒有設(shè)置默認(rèn)自動提交,需要主動提交,以保存所執(zhí)行的語句

connection.commit()

finally:

connection.close();

執(zhí)行查詢:


importdatetime

importpymysql.cursors

#連接配置信息

config={

'host':'127.0.0.1',

'port':3306,

'user':'root',

'password':'zhyea.com',

'db':'employees',

'charset':'utf8mb4',

'cursorclass':pymysql.cursors.DictCursor,

}

# 創(chuàng)建連接

connection=pymysql.connect(**config)

# 獲取雇傭日期

hire_start=datetime.date(1999,1,1)

hire_end=datetime.date(2016,12,31)

# 執(zhí)行sql語句

try:

withconnection.cursor()ascursor:

# 執(zhí)行sql語句,進行查詢

sql='SELECT first_name, last_name, hire_date FROM employees WHERE hire_date BETWEEN %s AND %s'

cursor.execute(sql,(hire_start,hire_end))

# 獲取查詢結(jié)果

result=cursor.fetchone()

print(result)

# 沒有設(shè)置默認(rèn)自動提交,需要主動提交,以保存所執(zhí)行的語句

connection.commit()

finally:

connection.close();

這里的查詢支取了一條查詢結(jié)果,查詢結(jié)果以字典的形式返回:



從結(jié)果集中獲取指定數(shù)目的記錄,可以使用fetchmany方法:

1result=cursor.fetchmany(2)

不過不建議這樣使用,最好在sql語句中設(shè)置查詢的記錄總數(shù)。

獲取全部結(jié)果集可以使用fetchall方法:

1result=cursor.fetchall()

因為只有兩條記錄,所以上面提到的這兩種查詢方式查到的結(jié)果是一樣的:

1[{'last_name':'Vanderkelen','hire_date':datetime.date(2015,8,12),'first_name':'Geert'},{'last_name':'Zhyea','hire_date':datetime.date(2015,8,21),'first_name':'Robin'}]

在django中使用

在django中使用是我找這個的最初目的。目前同時支持python3.4、django1.8的數(shù)據(jù)庫backend并不好找。這個是我目前找到的最好用的。

設(shè)置DATABASES和官方推薦使用的MySQLdb的設(shè)置沒什么區(qū)別:

DATABASES={

'default':{

'ENGINE':'django.db.backends.mysql',

'NAME':'mytest',

'USER':'root',

'PASSWORD':'zhyea.com',

'HOST':'127.0.0.1',

'PORT':'3306',

}

}

關(guān)鍵是這里:我們還需要在站點的__init__.py文件中添加如下的內(nèi)容:

importpymysql

pymysql.install_as_MySQLdb()

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容