python 專題九 Mysql數(shù)據(jù)庫(kù)編程基礎(chǔ)知識(shí)
在Python網(wǎng)絡(luò)爬蟲中,通常是通過TXT純文本方式存儲(chǔ),其實(shí)也是可以存儲(chǔ)在數(shù)據(jù)庫(kù)中的;同時(shí)在WAMP(Windows、Apache、MySQL、PHP或Python)開發(fā)網(wǎng)站中,也可以通過Python構(gòu)建網(wǎng)頁(yè)的,所以這篇文章主要講述Python調(diào)用MySQL數(shù)據(jù)庫(kù)相關(guān)編程知識(shí)。從以下幾個(gè)方面進(jìn)行講解:
1.配置MySLQ
2.SQL語(yǔ)句基礎(chǔ)知識(shí)
3.Python操作MySQL基礎(chǔ)知識(shí)
4.Python調(diào)用MySQL示例
一. 配置MySQL
首先下載mysql-5.0.96-winx64,安裝過程如下圖所示。
1.安裝MySQL 5.0
2.選擇手動(dòng)配置、服務(wù)類型、通用多功能型和安裝路徑
3.設(shè)置數(shù)據(jù)庫(kù)訪問量連接數(shù)為15、端口為3306(代碼中設(shè)置URL用到)、編碼方式為utf-8
4.設(shè)置默認(rèn)超級(jí)root用戶的用戶名和密碼,最后安裝成功
二. SQL語(yǔ)句基礎(chǔ)知識(shí)
安裝MySQL 5.0成功后,進(jìn)行數(shù)據(jù)庫(kù)的簡(jiǎn)單操作。
1.運(yùn)行MySQL輸入默認(rèn)用戶密碼123456
2.創(chuàng)建數(shù)據(jù)庫(kù)test01和使用數(shù)據(jù)庫(kù)(第二次調(diào)用直接use database)
create database test01;
顯示數(shù)據(jù)庫(kù)中包含的數(shù)據(jù)庫(kù):show databases;
3.創(chuàng)建表student,其中學(xué)號(hào)為主鍵
create table student(username varchar(20),password varchar(20),stuid int primary key);
4.顯示表結(jié)構(gòu),使用語(yǔ)句desc student
5.向?qū)W生表中插入數(shù)據(jù)并顯示查詢的數(shù)據(jù)
6.刪除表:drop table student;
7.更新數(shù)據(jù)
update student set password='000000' where stuid='1';
8.刪除數(shù)據(jù)
Delete from student where username='eastmount;
此時(shí)MySQL操作數(shù)據(jù)庫(kù)基本講解結(jié)束,你同樣可以實(shí)現(xiàn)數(shù)據(jù)庫(kù)的增刪改查、事務(wù)、存儲(chǔ)過程等操作,建議安裝可視化的軟件來替代黑框,或使用Navicat for MySQL軟件即可。代碼如下:
Enter password: ****** mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | test | | test01 | +--------------------+ 5 rows in set (0.00 sec) mysql> use test01; Database changed mysql> show tables; Empty set (0.00 sec) mysql> create table student(username varchar(20), -> password varchar(20), -> stuid int primary key); Query OK, 0 rows affected (0.33 sec) mysql> show tables; +------------------+ | Tables_in_test01 | +------------------+ | student | +------------------+ 1 row in set (0.00 sec) mysql> desc student; +----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+-------+ | username | varchar(20) | YES | | NULL | | | password | varchar(20) | YES | | NULL | | | stuid | int(11) | NO | PRI | NULL | | +----------+-------------+------+-----+---------+-------+ 3 rows in set (0.03 sec) mysql> insert student(username, password, stuid) -> values('eastmount','123456',1) -> ; Query OK, 1 row affected (0.05 sec) mysql> select * from student; +-----------+----------+-------+ | username | password | stuid | +-----------+----------+-------+ | eastmount | 123456 | 1 | +-----------+----------+-------+ 1 row in set (0.00 sec) mysql> update student set password='000000' where stuid='1'; Query OK, 1 row affected (0.10 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from student; +-----------+----------+-------+ | username | password | stuid | +-----------+----------+-------+ | eastmount | 000000 | 1 | +-----------+----------+-------+ 1 row in set (0.00 sec) mysql> delete from student where username='eastmount'; Query OK, 1 row affected (0.08 sec) mysql> select * from student; Empty set (0.00 sec) mysql>
三. Python調(diào)用MySQL基礎(chǔ)知識(shí)
通常的安裝方法是使用:pip install mysql 安裝Python的MySQL庫(kù),但是總會(huì)報(bào)錯(cuò)。常見錯(cuò)誤如:
Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat)
mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory
這些可能是驅(qū)動(dòng)等問題。
正確安裝方法:
建議下載一個(gè)MySQL-python-1.2.3.win-amd64-py2.7.exe文件進(jìn)行安裝。
官網(wǎng)地址:https://pypi.python.org/pypi/MySQL-python/
下載地址:http://chabaoo.cn/softs/73369.html
下面我們要詳細(xì)了解Python數(shù)據(jù)庫(kù)API。從Python中訪問數(shù)據(jù)庫(kù)需要接口程序,接口程序是一個(gè)Python模塊,它提供數(shù)據(jù)庫(kù)客戶端庫(kù)(通常是C語(yǔ)言寫成的)的接口供你訪問。注意:Python接口程序都一定要遵守Python DB-API規(guī)范。
DB-API是一個(gè)規(guī)范。它定義了一系列必須的對(duì)象和數(shù)據(jù)庫(kù)存取方式,以便為各種各樣的底層數(shù)據(jù)庫(kù)系統(tǒng)和多種多樣的數(shù)據(jù)庫(kù)接口程序提供一致的訪問接口。DB-API為不同的數(shù)據(jù)庫(kù)提供了一致的訪問接口,在不同的數(shù)據(jù)庫(kù)之間移植代碼成為一件輕松的事情。
下面簡(jiǎn)單介紹DB-API的使用方法。
1.模塊屬性
DB-API規(guī)范里的以下特性和屬性必須提供。一個(gè)DB-API兼容模塊定義如下所示:
apilevel:模塊兼容的DB-API版本號(hào) threadsafety:線程安全級(jí)別 paramstyle:支持sql語(yǔ)句參數(shù)風(fēng)格 connect():連接數(shù)據(jù)庫(kù)
Python調(diào)用MsSQL需要導(dǎo)入MySQLdb庫(kù),如下:
import MySQLdb
2.connect()函數(shù)
其中主要使用的方法是connect對(duì)象。connect()方法生成一個(gè)connect對(duì)象,用于訪問數(shù)據(jù)庫(kù),其參數(shù)如下:
user:Username password:Password host:Hostname database:DatabaseName dsn:Data source name
注意并非所有的接口程序都嚴(yán)格按照這種格式,如MySQLdb。
import MySQLdb conn = MySQLdb.connect(host='localhost', db='test01', user='root', passwd='123456', port=3306, charset='utf8')
connect()對(duì)象方法如下:
close():關(guān)閉數(shù)據(jù)庫(kù)連接,或者關(guān)閉游標(biāo)對(duì)象 commit():提交當(dāng)前事務(wù) rollback():取消當(dāng)前事務(wù) cursor():創(chuàng)建游標(biāo)或類游標(biāo)對(duì)象 errorhandler(cxn,errcls,errval):作為已給游標(biāo)的句柄
注意,執(zhí)行close()方法則上述的連接對(duì)象方法不能再使用,否則發(fā)生異常。commit()、rollback()、cursor()或許更對(duì)于支持事務(wù)的數(shù)據(jù)庫(kù)更有意義。
數(shù)據(jù)庫(kù)事務(wù)(Database Transaction) ,是指作為單個(gè)邏輯工作單元執(zhí)行的一系列操作,要么完整地執(zhí)行,要么完全地不執(zhí)行。 一旦你完成了數(shù)據(jù)庫(kù)連接,關(guān)閉了游標(biāo)對(duì)象,然后在執(zhí)行commit()提交你的操作,然后關(guān)閉連接。
3.游標(biāo)對(duì)象
上面說了connect()方法用于提供連接數(shù)據(jù)庫(kù)的接口,如果要對(duì)數(shù)據(jù)庫(kù)操作那么還需要使用游標(biāo)對(duì)象。游標(biāo)對(duì)象的屬性和方法:
fetchone():可以看作fetch(取出) one(一個(gè)),也就是得到結(jié)果集的下一行(一行)。 fetchmany(size):可以看作fetch(取出)many(多個(gè)),這里的參數(shù)是界限,得到結(jié)果集的下幾行(幾行) fetchall():顧名思義,取得所有。 execute(sql):執(zhí)行數(shù)據(jù)庫(kù)操作,參數(shù)為sql語(yǔ)句。 close():不需要游標(biāo)時(shí)盡可能的關(guān)閉
下面通過簡(jiǎn)單的示例進(jìn)行講解。
四. Python調(diào)用MySQL示例
在前面數(shù)據(jù)庫(kù)中我們創(chuàng)建了數(shù)據(jù)庫(kù)“test01”和表“student”,同時(shí)插入了數(shù)據(jù)。那么,怎樣通過Python來顯示呢?
1.查詢所有數(shù)據(jù)庫(kù)
首先,我們查看本地?cái)?shù)據(jù)庫(kù)中所包含的數(shù)據(jù)庫(kù)名稱,通過“show databases”語(yǔ)句。
import MySQLdb try: conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306) cur=conn.cursor() res = cur.execute('show databases') print res for data in cur.fetchall(): print '%s' % data cur.close() conn.close() except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0], e.args[1])
其中通過鏈接數(shù)據(jù)庫(kù)代碼為:
conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306)
訪問root超級(jí)用戶,其密碼為“123456”,端口為“3306”,其結(jié)果如下:
如果不知道本地?cái)?shù)據(jù)庫(kù)的名稱,可以通過該方法,先查詢數(shù)據(jù)庫(kù)中包含哪些數(shù)據(jù)庫(kù),然后再連接該數(shù)據(jù)庫(kù)進(jìn)行相關(guān)的操作。
2.查詢表
下面介紹查詢表student中數(shù)據(jù),代碼如下,代碼的具體含義是通過connect()連接數(shù)據(jù)庫(kù),通過conn.cursor()定義游標(biāo),然后調(diào)用游標(biāo)的excute(sql)執(zhí)行數(shù)據(jù)庫(kù)操作,此處為查詢操作,再通過fetchall()函數(shù)獲取所有數(shù)據(jù)。
# coding:utf-8 import MySQLdb try: conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306, db='test01', charset='utf8') cur=conn.cursor() res = cur.execute('select * from student') print u'表中包含',res,u'條數(shù)據(jù)\n' print u'數(shù)據(jù)如下:(姓名 密碼 序號(hào))' for data in cur.fetchall(): print '%s %s %s' % data cur.close() conn.close() except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0], e.args[1])
輸出結(jié)果如圖所示:
對(duì)應(yīng)的MySQL中的結(jié)果是一致的,下圖是對(duì)應(yīng)的結(jié)果。
3.創(chuàng)建表
下面這段代碼是創(chuàng)建一張教師表,主要是通過commit()提交數(shù)據(jù)。
# coding:utf-8 import MySQLdb try: conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306, db='test01', charset='utf8') cur=conn.cursor() #查看表 print u'插入前包含表:' cur.execute('show tables') for data in cur.fetchall(): print '%s' % data #插入數(shù)據(jù) sql = '''create table teacher(id int not null primary key auto_increment, name char(30) not null, sex char(20) not null )''' cur.execute(sql) #查看表 print u'\n插入后包含表:' cur.execute('show tables') for data in cur.fetchall(): print '%s' % data cur.close() conn.commit() conn.close() except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0], e.args[1])
輸出結(jié)果如下所示,插入教師表,包含字段:教師序號(hào)(id)、教師名稱(name)、教師性別(sex)。
插入數(shù)據(jù)也可以通過execute(sql)方法實(shí)現(xiàn),如:
cur.execute("insert into student values( 'yxz', '111111', '10')")
但插入的新數(shù)據(jù)通常是通過變量進(jìn)行賦值,而不是固定的,所以要對(duì)這條語(yǔ)句中的值做修改。我們可以做如下修改:
# coding:utf-8 import MySQLdb try: conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306, db='test01') cur=conn.cursor() #插入數(shù)據(jù) sql = '''insert into student values(%s, %s, %s)''' cur.execute(sql, ('yxz','111111', '10')) #查看數(shù)據(jù) print u'\n插入數(shù)據(jù):' cur.execute('select * from student') for data in cur.fetchall(): print '%s %s %s' % data cur.close() conn.commit() conn.close() except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0], e.args[1])
輸出結(jié)果如下所示:
>>> 插入數(shù)據(jù): esatmount 123456 1 yangxiuzhang 123456 2 xiaoy 123456 3 yxz 111111 10 >>>
同樣,對(duì)數(shù)據(jù)庫(kù)的增刪改插都可以進(jìn)行,請(qǐng)讀者自行閱讀。
推薦資料:python使用mysql數(shù)據(jù)庫(kù) - 蟲師
后面我會(huì)結(jié)合Python爬蟲講述,如何將爬取的內(nèi)容存儲(chǔ)在數(shù)據(jù)庫(kù)中,如我CSDN的博客,爬取博客標(biāo)題、發(fā)布時(shí)間、閱讀量和評(píng)論數(shù)。
MySQL數(shù)據(jù)庫(kù)中結(jié)果如下圖所示:
最后希望文章對(duì)你有所幫助,如果文章中存在不足或錯(cuò)誤的地方,還請(qǐng)海涵~還是那句話,挺享受現(xiàn)在的老師生活,不論科研、項(xiàng)目,還是教學(xué),很充實(shí),加油!
- php基礎(chǔ)之連接mysql數(shù)據(jù)庫(kù)和查詢數(shù)據(jù)
- PHP連接和操作MySQL數(shù)據(jù)庫(kù)基礎(chǔ)教程
- Mysql入門基礎(chǔ) 數(shù)據(jù)庫(kù)創(chuàng)建篇
- PHP5 操作MySQL數(shù)據(jù)庫(kù)基礎(chǔ)代碼
- mysql 8.0.15 安裝圖文教程及數(shù)據(jù)庫(kù)基礎(chǔ)
- MySQL數(shù)據(jù)庫(kù)基礎(chǔ)命令大全(收藏)
- 很全面的Mysql數(shù)據(jù)庫(kù)、數(shù)據(jù)庫(kù)表、數(shù)據(jù)基礎(chǔ)操作筆記(含代碼)
- mysql 數(shù)據(jù)庫(kù)基礎(chǔ)筆記
- mysql數(shù)據(jù)庫(kù)基礎(chǔ)知識(shí)點(diǎn)與操作小結(jié)
- MySQL數(shù)據(jù)庫(kù)基礎(chǔ)入門之常用命令小結(jié)
- MySQL數(shù)據(jù)庫(kù)基礎(chǔ)篇之入門基礎(chǔ)命令小結(jié)
- MySql數(shù)據(jù)庫(kù)基礎(chǔ)知識(shí)點(diǎn)總結(jié)
相關(guān)文章
淺析form標(biāo)簽中的GET和POST提交方式區(qū)別
在HTML中,form表單的作用是收集標(biāo)簽中的內(nèi)容<form>...</form> 中間可以由訪問者添加類似于文本,選擇,或者一些控制模塊等等.然后這些內(nèi)容將會(huì)被送到服務(wù)端2021-09-09python畫圖——實(shí)現(xiàn)在圖上標(biāo)注上具體數(shù)值的方法
今天小編就為大家分享一篇python畫圖——實(shí)現(xiàn)在圖上標(biāo)注上具體數(shù)值的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-07-07python curl2pyreqs 生成接口腳本實(shí)戰(zhàn)教程
這篇文章主要介紹了python curl2pyreqs 生成接口腳本實(shí)戰(zhàn)教程,首先下載 curl2pyreqs 庫(kù),打開調(diào)試模式,在Network這里獲取接口的cURL,需要的朋友可以參考下2023-10-10Pycharm代碼無法復(fù)制,無法選中刪除,無法編輯的解決方法
今天小編就為大家分享一篇Pycharm代碼無法復(fù)制,無法選中刪除,無法編輯的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-10-10python爬蟲MeterSphere平臺(tái)執(zhí)行報(bào)告流程解析
這篇文章主要為大家介紹了python爬蟲MeterSphere平臺(tái)執(zhí)行報(bào)告流程解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12利用python將json數(shù)據(jù)轉(zhuǎn)換為csv格式的方法
下面小編就為大家分享一篇利用python將json數(shù)據(jù)轉(zhuǎn)換為csv格式的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03pycharm利用pyspark遠(yuǎn)程連接spark集群的實(shí)現(xiàn)
由于工作需要,利用spark完成機(jī)器學(xué)習(xí)。因此需要對(duì)spark集群進(jìn)行操作。所以利用pycharm和pyspark遠(yuǎn)程連接spark集群。感興趣的可以了解一下2021-05-05