一步一步教你如何用Python操作MySQL
工欲善其事,必先利其器。所以***步,我們先下載第三方庫。在這里,我用到的是pymysql庫。
下載庫:在命令行輸入
pip install pymysql
下載后可檢驗一下是否成功下載。直接在命令行進(jìn)入python然后導(dǎo)庫即可
C:\Users\June>python
Python 3.6.3 |Anaconda, Inc.| (default, Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymysql
>>>
看到這個畫面就說明下載成功了,接下來學(xué)習(xí)如何操作數(shù)據(jù)庫了?。。?/p>
連接數(shù)據(jù)庫
import pymysql
# 連接數(shù)據(jù)庫
db = pymysql.connect(host='127.0.0.1',user='root',passwd='your password',db='news',port=3306,charset='utf8')
以上的參數(shù)是必填的
- host: 這個是ip地址,因為我這里是本地的,所以填127.0.0.1,也可以填localhost。
- user:用戶名,如果你也是本地的,就填root好了
- passwd:這個是密碼,填上你自己設(shè)的密碼就可以了
- db:這個是數(shù)據(jù)庫名,我這里選的是news數(shù)據(jù)庫
- port:這個是端口,本地的一般都是3306
- charset:這個是編碼方式,要和你數(shù)據(jù)庫的編碼方式一致,要不會連接失敗
連接上了,怎么驗證呢?這里我們可以選擇查一條數(shù)據(jù)
try:
db = pymysql.connect(host='127.0.0.1',user='root',passwd='your password',db='news',port=3306,charset='utf8')
# 檢驗數(shù)據(jù)庫是否連接成功
cursor = db.cursor()
# 這個是執(zhí)行sql語句,返回的是影響的條數(shù)
data = cursor.execute('SELECT * FROM `new`')
# 得到一條數(shù)據(jù)
one = cursor.fetchone()
print(data)
print(one)
except pymysql.Error as e:
print(e)
print('操作數(shù)據(jù)庫失敗')
finally:
# 如果連接成功就要關(guān)閉數(shù)據(jù)庫
if db:
db.close()
代碼解讀:因為在連接數(shù)據(jù)庫中,有時會發(fā)生連接失敗等異常,所以這里就進(jìn)行捕捉異常,這里的異常都是在 pymsql.Error 里面。上面的代碼看不懂也沒關(guān)系,因為我接下來會說,如果運行后有結(jié)果證明連接成功。
在用完后,一定要記得關(guān)閉數(shù)據(jù)庫連接,防止資源泄露問題。
對數(shù)據(jù)進(jìn)行查詢
import pymysql
try:
conn = pymysql.connect(host='127.0.0.1',user='root',passwd='password',db='news',charset='utf8',port=3306)
# 這個是光標(biāo),用來操作數(shù)據(jù)庫語句
cursor = conn.cursor()
# 執(zhí)行sql語句
cursor.execute('SELECT * FROM `new`')
print(cursor.fetchone())
# 關(guān)閉光標(biāo)
cursor.close()
except pymysql.Error as e:
print(e)
print('操作數(shù)據(jù)庫失敗')
finally:
if conn:
conn.close()
代碼解讀:
- cursor():這個是光標(biāo),用來執(zhí)行mysql語句的,用完后也是需要關(guān)閉的
- excute():這個是執(zhí)行語句,執(zhí)行參數(shù)的mysql語句
- fetchone():這個是查看執(zhí)行語句后的一條數(shù)據(jù)
- fetchall():這個是查看所有數(shù)據(jù)
在查詢數(shù)據(jù)后,返回的是一整條數(shù)據(jù),有沒有可以按字典形式來查詢的呢?來試試!
print(cursor.fetchone()['name'])
Traceback (most recent call last):
File "E:/anaconda/python_project/mysql_test/test2.py", line 8, in <module>
print(cursor.fetchone()['name'])
TypeError: tuple indices must be integers or slices, not str
查了之后,編譯器想都不想就給了我這個錯誤,說這是個元組,不能這樣操作。
雖然python沒有提供,但是我們可以手動轉(zhuǎn)成字典來查詢啊
cursor這里有個屬性:description。獲取的是數(shù)據(jù)庫每個欄位情況,如下:
print(cursor.description)
# 下面是結(jié)果
(('id', 3, None, 11, 11, 0, False), ('type', 253, None, 5, 5, 0, False), ('title', 253, None, 50, 50, 0, False), ('content', 253, None, 2000, 2000, 0, False), ('view_count', 3, None, 11, 11, 0, False), ('release_time', 12, None, 19, 19, 0, False), ('author', 253, None, 20, 20, 0, True), ('from', 253, None, 20, 20, 0, True), ('is_valibale', 3, None, 11, 11, 0, False)
所以,我們利用這個屬性手動生成字典
# 將一條數(shù)據(jù)轉(zhuǎn)成字典方便查找
new = dict(zip([x[0] for x in cursor.description],[x for x in cursor.fetchone()]))
print(new)
# 下面是結(jié)果
{'id': 2, 'type': 'NBA', 'title': '考辛斯跟腱撕裂賽季報銷 濃眉詹皇發(fā)聲祝福', 'content': '他遭遇左腳跟腱撕裂,將缺席賽季剩下的比賽。這無疑對考辛斯和鵜鶘隊都是一個重大的打擊', 'view_count': 3560, 'release_time': datetime.datetime(2018, 1, 27, 12, 10), 'author': 'xiaoylin', 'from': '騰訊體育', 'is_valibale': 1}
這里利用zip函數(shù)和列表生成式來一行代碼就生成成功了
用字典來查詢,現(xiàn)在就可以了
print(new['title'])
# 下面是結(jié)果
考辛斯跟腱撕裂賽季報銷 濃眉詹皇發(fā)聲祝福
但是,上面的只是一條數(shù)據(jù)的,如果是多條的呢?再按上面的方法就行不通了。這時就需要用到map函數(shù)了
def new2dict(new):
return dict(zip([x[0] for x in cursor.description],[x for x in new]))
news_list = list(map(new2dict,cursor.fetchall()))
print(news_list)
# 下面是結(jié)果
[{'id': 2, 'type': 'NBA', 'title': '考辛斯跟腱撕裂賽季報銷 濃眉詹皇發(fā)聲祝福', 'content': '他遭遇左腳跟腱撕裂,將缺席賽季剩下的比賽。這無疑對考辛斯和鵜鶘隊都是一個重大的打擊', 'view_count': 3560, 'release_time': datetime.datetime(2018, 1, 27, 12, 10), 'author': 'xiaoylin', 'from': '騰訊體育', 'is_valibale': 1}, {'id': 3, 'type': 'NBA', 'title': '火箭挖21分大哈登得背鍋 連遭濃眉大帽太尷尬', 'content': '火箭在客場以113-115惜敗于鵜鶘,4連勝終結(jié)。詹姆斯-哈登出戰(zhàn)34分鐘16投5中,其中三分球9投只有1中,罰球14罰12中,拿到23分、11助攻、5籃板但也有4次失誤,其在場正負(fù)值為尷尬的-12分', 'view_count': 7520, 'release_time': datetime.datetime(2018, 1, 27, 12, 5), 'author': 'youngcao', 'from': '騰訊體育','is_valibale': 1}, {'id': 4, 'type': '英超', 'title': '足總杯-曼聯(lián)4-0英乙球隊晉級 桑神首秀造兩球', 'content': '2017-18賽季英格蘭足總杯第4輪,曼聯(lián)客場4比0擊敗英乙球隊約維爾,順利晉級下一輪。桑切斯迎來曼聯(lián)首秀,并制造了兩個入球', 'view_count': 6560, 'release_time': datetime.datetime(2018, 1, 27, 5, 49), 'author': 'ricazhang', 'from': '騰訊體育','is_valibale': 1}, {'id': 5, 'type': '英超', 'title': '這才配紅魔7號!桑神首秀大腿級表演 回?fù)魢u聲質(zhì)疑', 'content': '在今天凌晨對陣約維爾的首秀也值得期待。雖然在登場的72分鐘時間里沒有進(jìn)球,但送出1次助攻且有有6次威脅傳球的數(shù)據(jù)還是十分亮眼', 'view_count': 2760, 'release_time': datetime.datetime(2018, 1, 27, 6, 13), 'author': 'yaxinhao', 'from': '騰訊體育', 'is_valibale': 1}]
這里很巧妙的利用了map函數(shù),因為多條數(shù)據(jù)就可以進(jìn)行迭代了,需要操作每條數(shù)據(jù),這樣就可以想到map函數(shù)
接下來我們再用面向?qū)ο蟮姆椒▉碛胮ython進(jìn)行查詢數(shù)據(jù)庫
import pymysql
class MysqlSearch(object):
def get_conn(self):
'''連接mysql數(shù)據(jù)庫'''
try:
self.conn = pymysql.connect(host='127.0.0.1',user='root',passwd='your password',port=3306,charset='utf8',db='news')
except pymysql.Error as e:
print(e)
print('連接數(shù)據(jù)庫失敗')
def close_conn(self):
'''關(guān)閉數(shù)據(jù)庫'''
try:
if self.conn:
self.conn.close()
except pymysql.Error as e:
print(e)
print('關(guān)閉數(shù)據(jù)庫失敗')
def get_one(self):
'''查詢一條數(shù)據(jù)'''
try:
# 這個是連接數(shù)據(jù)庫
self.get_conn()
# 查詢語句
sql = 'SELECT * FROM `new` WHERE `type`=%s'
# 這個光標(biāo)用來執(zhí)行sql語句
cursor = self.conn.cursor()
cursor.execute(sql,('英超',))
new = cursor.fetchone()
# 返回一個字典,讓用戶可以按數(shù)據(jù)類型來獲取數(shù)據(jù)
new_dict = dict(zip([x[0] for x in cursor.description],new))
# 關(guān)閉cursor
cursor.close()
self.close_conn()
return new_dict
except AttributeError as e:
print(e)
return None
def get_all(self):
'''獲取所有結(jié)果'''
sql = 'SELECT * FROM `new` '
self.get_conn()
try:
cursor = self.conn.cursor()
cursor.execute(sql)
news = cursor.fetchall()
# 將數(shù)據(jù)轉(zhuǎn)為字典,讓用戶根據(jù)鍵來查數(shù)據(jù)
news_list =list(map(lambda x:dict(zip([x[0] for x in cursor.description],[d for d in x])),news))
# 這樣也行,連續(xù)用兩個列表生成式
news_list = [dict(zip([x[0] for x in cursor.description],row)) for row in news]
cursor.close()
self.close_conn()
return news_list
except AttributeError as e:
print(e)
return None
def main():
# 獲取一條數(shù)據(jù)
news = MysqlSearch()
new = news.get_one()
if new:
print(new)
else:
print('操作失敗')
# 獲取多條數(shù)據(jù)
news = MysqlSearch()
rest = news.get_all()
if rest:
print(rest)
print(rest[7]['type'],rest[7]['title'])
print('類型:{0},標(biāo)題:{1}'.format(rest[12]['type'],rest[12]['title']))
for row in rest:
print(row)
else:
print('沒有獲取到數(shù)據(jù)')
if __name__ == '__main__':
main()
這樣就可以通過實例的方法來進(jìn)行查詢數(shù)據(jù)庫了
我們還可以根據(jù)頁數(shù)來進(jìn)行查詢指定的數(shù)據(jù)數(shù)
def get_more(self,page,page_size):
'''查多少頁的多少條數(shù)據(jù)'''
offset = (page-1)*page_size
sql = 'SELECT * FROM `new` LIMIT %s,%s'
try:
self.get_conn()
cursor = self.conn.cursor()
cursor.execute(sql,(offset,page_size,))
news = [dict(zip([x[0] for x in cursor.description],new)) for new in cursor.fetchall()]
cursor.close()
self.close_conn()
return news
except AttributeError as e:
print(e)
return None
def main():
#獲取某頁的數(shù)據(jù)
news = MysqlSearch()
new = news.get_more(3,5)
if new:
for row in new:
print(row)
else:
print('獲取數(shù)據(jù)失敗')
if __name__ == '__main__':
main()
利用的是mysql的limit關(guān)鍵字,還有其他的,比如進(jìn)行排序分組的感興趣的可以自己嘗試下
增加數(shù)據(jù)到數(shù)據(jù)庫
def add_one(self):
sql = 'INSERT INTO `new`(`title`,`content`,`type`,`view_count`,`release_time`) VALUE(%s,%s,%s,%s,%s)'
try:
self.get_conn()
cursor = self.conn.cursor()
cursor.execute(sql, ('title', 'content', 'type', '1111', '2018-02-01'))
cursor.execute(sql, ('標(biāo)題', '內(nèi)容', '類型', '0000', '2018-02-01'))
# 一定需要提交事務(wù),要不不會顯示,只會占位在數(shù)據(jù)庫
self.conn.commit()
return 1
except AttributeError as e:
print('Error:', e)
return 0
except TypeError as e:
print('Error:', e)
# 發(fā)生錯誤還提交就是把執(zhí)行正確的語句提交上去
# self.conn.commit()
# 下面這個方法是發(fā)生異常就全部不能提交,但語句執(zhí)行成功的就會占位
self.conn.rollback()
return 0
finally:
cursor.close()
self.close_conn()
def main():
news = OperateSQL()
if news.add_one():
print('增加數(shù)據(jù)成功')
else:
print('發(fā)生異常,請檢查?。?!')
if __name__ == '__main__':
main()
因為是增加數(shù)據(jù),所以需要提交事務(wù),這就需要用到conn .commit()來進(jìn)行提交,在增加數(shù)據(jù)后,如果不提交,數(shù)據(jù)庫就不會顯示。
還有修改數(shù)據(jù)和刪除數(shù)據(jù)就不貼出來了,只是把上面的sql變量的語句改成修改或者刪除的語句就可以了,如果你還不會,建議練習(xí)下