[python学习] 专题九.Mysql数据库编程基础知识
? ? ? ? 在Python網(wǎng)絡(luò)爬蟲中,通常是通過TXT純文本方式存儲(chǔ),其實(shí)也是可以存儲(chǔ)在數(shù)據(jù)庫中的;同時(shí)在WAMP(Windows、Apache、MySQL、PHP或Python)開發(fā)網(wǎng)站中,也可以通過Python構(gòu)建網(wǎng)頁的,所以這篇文章主要講述Python調(diào)用MySQL數(shù)據(jù)庫相關(guān)編程知識(shí)。從以下幾個(gè)方面進(jìn)行講解:
? ? ? ? 1.配置MySLQ
? ? ? ? 2.SQL語句基礎(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ù)庫訪問量連接數(shù)為15、端口為3306(代碼中設(shè)置URL用到)、編碼方式為utf-8
?? ? ? ??4.設(shè)置默認(rèn)超級(jí)root用戶的用戶名和密碼,最后安裝成功
?
二. SQL語句基礎(chǔ)知識(shí)
? ? ? ? 安裝MySQL 5.0成功后,進(jìn)行數(shù)據(jù)庫的簡單操作。
? ? ? ??1.運(yùn)行MySQL輸入默認(rèn)用戶密碼123456
? ? ? ? ?2.創(chuàng)建數(shù)據(jù)庫test01和使用數(shù)據(jù)庫(第二次調(diào)用直接use database)
? ? ? ?? create database test01;
? ? ? ??顯示數(shù)據(jù)庫中包含的數(shù)據(jù)庫: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),使用語句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ù)庫基本講解結(jié)束,你同樣可以實(shí)現(xiàn)數(shù)據(jù)庫的增刪改查、事務(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: 0mysql> 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庫,但是總會(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://download.csdn.net/detail/eastmount/9598651
?
? ? ? ? 下面我們要詳細(xì)了解Python數(shù)據(jù)庫API。從Python中訪問數(shù)據(jù)庫需要接口程序,接口程序是一個(gè)Python模塊,它提供數(shù)據(jù)庫客戶端庫(通常是C語言寫成的)的接口供你訪問。注意:Python接口程序都一定要遵守Python DB-API規(guī)范。
? ? ? ? DB-API是一個(gè)規(guī)范。它定義了一系列必須的對象和數(shù)據(jù)庫存取方式,以便為各種各樣的底層數(shù)據(jù)庫系統(tǒng)和多種多樣的數(shù)據(jù)庫接口程序提供一致的訪問接口。DB-API為不同的數(shù)據(jù)庫提供了一致的訪問接口,在不同的數(shù)據(jù)庫之間移植代碼成為一件輕松的事情。
? ? ? ? ?下面簡單介紹DB-API的使用方法。
? ? ? ? 1.模塊屬性
? ? ? ??DB-API規(guī)范里的以下特性和屬性必須提供。一個(gè)DB-API兼容模塊定義如下所示: apilevel:模塊兼容的DB-API版本號(hào) threadsafety:線程安全級(jí)別 paramstyle:支持sql語句參數(shù)風(fēng)格 connect():連接數(shù)據(jù)庫
? ? ? ? Python調(diào)用MsSQL需要導(dǎo)入MySQLdb庫,如下:
import MySQLdb? ? ? ? 2.connect()函數(shù)
? ? ? ??其中主要使用的方法是connect對象。connect()方法生成一個(gè)connect對象,用于訪問數(shù)據(jù)庫,其參數(shù)如下:
? ? ? ? 注意并非所有的接口程序都嚴(yán)格按照這種格式,如MySQLdb。
import MySQLdb conn = MySQLdb.connect(host='localhost', db='test01', user='root', passwd='123456', port=3306, charset='utf8')? ? ? ? connect()對象方法如下:
lose():關(guān)閉數(shù)據(jù)庫連接,或者關(guān)閉游標(biāo)對象 commit():提交當(dāng)前事務(wù) rollback():取消當(dāng)前事務(wù) cursor():創(chuàng)建游標(biāo)或類游標(biāo)對象 errorhandler(cxn,errcls,errval):作為已給游標(biāo)的句柄? ? ? ? 注意,執(zhí)行close()方法則上述的連接對象方法不能再使用,否則發(fā)生異常。commit()、rollback()、cursor()或許更對于支持事務(wù)的數(shù)據(jù)庫更有意義。
? ? ? ? 數(shù)據(jù)庫事務(wù)(Database Transaction) ,是指作為單個(gè)邏輯工作單元執(zhí)行的一系列操作,要么完整地執(zhí)行,要么完全地不執(zhí)行。 一旦你完成了數(shù)據(jù)庫連接,關(guān)閉了游標(biāo)對象,然后在執(zhí)行commit()提交你的操作,然后關(guān)閉連接。
? ? ? ? 3.游標(biāo)對象
? ? ? ??上面說了connect()方法用于提供連接數(shù)據(jù)庫的接口,如果要對數(shù)據(jù)庫操作那么還需要使用游標(biāo)對象。游標(biāo)對象的屬性和方法:
? ? ? ? 下面通過簡單的示例進(jìn)行講解。
四. Python調(diào)用MySQL示例
? ? ? ? 在前面數(shù)據(jù)庫中我們創(chuàng)建了數(shù)據(jù)庫“test01”和表“student”,同時(shí)插入了數(shù)據(jù)。那么,怎樣通過Python來顯示呢?
? ? ? ?1.查詢所有數(shù)據(jù)庫
? ? ? ? 首先,我們查看本地?cái)?shù)據(jù)庫中所包含的數(shù)據(jù)庫名稱,通過“show databases”語句。
? ? ? ? 其中通過鏈接數(shù)據(jù)庫代碼為:
conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306)
? ? ? ? 訪問root超級(jí)用戶,其密碼為“123456”,端口為“3306”,其結(jié)果如下:
? ? ? ? 如果不知道本地?cái)?shù)據(jù)庫的名稱,可以通過該方法,先查詢數(shù)據(jù)庫中包含哪些數(shù)據(jù)庫,然后再連接該數(shù)據(jù)庫進(jìn)行相關(guān)的操作。
? ? ? ? 2.查詢表
? ? ? ? 下面介紹查詢表student中數(shù)據(jù),代碼如下,代碼的具體含義是通過connect()連接數(shù)據(jù)庫,通過conn.cursor()定義游標(biāo),然后調(diào)用游標(biāo)的excute(sql)執(zhí)行數(shù)據(jù)庫操作,此處為查詢操作,再通過fetchall()函數(shù)獲取所有數(shù)據(jù)。
? ? ? ? 輸出結(jié)果如圖所示:
? ? ? ? 對應(yīng)的MySQL中的結(jié)果是一致的,下圖是對應(yīng)的結(jié)果。
? ? ? ? 3.創(chuàng)建表? ? ? ? 下面這段代碼是創(chuàng)建一張教師表,主要是通過commit()提交數(shù)據(jù)。 # coding:utf-8 import MySQLdbtry: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' % datacur.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)行賦值,而不是固定的,所以要對這條語句中的值做修改。我們可以做如下修改:
? ? ? ? 同樣,對數(shù)據(jù)庫的增刪改插都可以進(jìn)行,請讀者自行閱讀。
? ? ? ? 推薦資料:python使用mysql數(shù)據(jù)庫 - 蟲師
? ? ? ? 后面我會(huì)結(jié)合Python爬蟲講述,如何將爬取的內(nèi)容存儲(chǔ)在數(shù)據(jù)庫中,如我CSDN的博客,爬取博客標(biāo)題、發(fā)布時(shí)間、閱讀量和評(píng)論數(shù)。
?
?
? ? ? ? 最后希望文章對你有所幫助,如果文章中存在不足或錯(cuò)誤的地方,還請海涵~還是那句話,挺享受現(xiàn)在的老師生活,不論科研、項(xiàng)目,還是教學(xué),很充實(shí),加油!
? ? ? ??但行好事,莫問前程。
? ? ? ? 待隨滿天李桃,再追學(xué)友趣事。
? ? ? ? (By:Eastmount 2016-08-10 晚上10點(diǎn)??http://blog.csdn.net/eastmount/?)
?
?
總結(jié)
以上是生活随笔為你收集整理的[python学习] 专题九.Mysql数据库编程基础知识的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [python] 使用scikit-le
- 下一篇: [数据库] MySQL基础知识之日期判断