欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python 專題九 Mysql數(shù)據(jù)庫編程基礎(chǔ)知識

 更新時間:2017年03月16日 15:17:55   作者:Eastmount  
在Python網(wǎng)絡(luò)爬蟲中,通常是通過TXT純文本方式存儲,其實也是可以存儲在數(shù)據(jù)庫中的;同時在WAMP(Windows、Apache、MySQL、PHP或Python)開發(fā)網(wǎng)站中,也可以通過Python構(gòu)建網(wǎng)頁的,所以這篇文章主要講述Python調(diào)用MySQL數(shù)據(jù)庫相關(guān)編程知識

在Python網(wǎng)絡(luò)爬蟲中,通常是通過TXT純文本方式存儲,其實也是可以存儲在數(shù)據(jù)庫中的;同時在WAMP(Windows、Apache、MySQL、PHP或Python)開發(fā)網(wǎng)站中,也可以通過Python構(gòu)建網(wǎng)頁的,所以這篇文章主要講述Python調(diào)用MySQL數(shù)據(jù)庫相關(guān)編程知識。從以下幾個方面進(jìn)行講解:

1.配置MySLQ
2.SQL語句基礎(chǔ)知識
3.Python操作MySQL基礎(chǔ)知識
4.Python調(diào)用MySQL示例

一. 配置MySQL

        
        首先下載mysql-5.0.96-winx64,安裝過程如下圖所示。
        1.安裝MySQL 5.0
 

 

        2.選擇手動配置、服務(wù)類型、通用多功能型和安裝路徑
 

 

        3.設(shè)置數(shù)據(jù)庫訪問量連接數(shù)為15、端口為3306(代碼中設(shè)置URL用到)、編碼方式為utf-8
 

 

        4.設(shè)置默認(rèn)超級root用戶的用戶名和密碼,最后安裝成功
 

二. SQL語句基礎(chǔ)知識


        安裝MySQL 5.0成功后,進(jìn)行數(shù)據(jù)庫的簡單操作。
        1.運行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é)號為主鍵
         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;

        此時MySQL操作數(shù)據(jù)庫基本講解結(jié)束,你同樣可以實現(xiàn)數(shù)據(jù)庫的增刪改查、事務(wù)、存儲過程等操作,建議安裝可視化的軟件來替代黑框,或使用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ǔ)知識

通常的安裝方法是使用:pip install mysql 安裝Python的MySQL庫,但是總會報錯。常見錯誤如:
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ū)動等問題。

正確安裝方法:
建議下載一個MySQL-python-1.2.3.win-amd64-py2.7.exe文件進(jìn)行安裝。
官網(wǎng)地址:https://pypi.python.org/pypi/MySQL-python/
下載地址:http://www.dbjr.com.cn/softs/73369.html

下面我們要詳細(xì)了解Python數(shù)據(jù)庫API。從Python中訪問數(shù)據(jù)庫需要接口程序,接口程序是一個Python模塊,它提供數(shù)據(jù)庫客戶端庫(通常是C語言寫成的)的接口供你訪問。注意:Python接口程序都一定要遵守Python DB-API規(guī)范。
DB-API是一個規(guī)范。它定義了一系列必須的對象和數(shù)據(jù)庫存取方式,以便為各種各樣的底層數(shù)據(jù)庫系統(tǒng)和多種多樣的數(shù)據(jù)庫接口程序提供一致的訪問接口。DB-API為不同的數(shù)據(jù)庫提供了一致的訪問接口,在不同的數(shù)據(jù)庫之間移植代碼成為一件輕松的事情。

下面簡單介紹DB-API的使用方法。

1.模塊屬性
DB-API規(guī)范里的以下特性和屬性必須提供。一個DB-API兼容模塊定義如下所示:

apilevel:模塊兼容的DB-API版本號
threadsafety:線程安全級別
paramstyle:支持sql語句參數(shù)風(fēng)格
connect():連接數(shù)據(jù)庫

Python調(diào)用MsSQL需要導(dǎo)入MySQLdb庫,如下:

import MySQLdb

 2.connect()函數(shù)

其中主要使用的方法是connect對象。connect()方法生成一個connect對象,用于訪問數(shù)據(jù)庫,其參數(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()對象方法如下:

close():關(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) ,是指作為單個邏輯工作單元執(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)對象的屬性和方法:

fetchone():可以看作fetch(取出) one(一個),也就是得到結(jié)果集的下一行(一行)。
fetchmany(size):可以看作fetch(取出)many(多個),這里的參數(shù)是界限,得到結(jié)果集的下幾行(幾行)
fetchall():顧名思義,取得所有。
execute(sql):執(zhí)行數(shù)據(jù)庫操作,參數(shù)為sql語句。
close():不需要游標(biāo)時盡可能的關(guān)閉

下面通過簡單的示例進(jìn)行講解。

四. Python調(diào)用MySQL示例

在前面數(shù)據(jù)庫中我們創(chuàng)建了數(shù)據(jù)庫“test01”和表“student”,同時插入了數(shù)據(jù)。那么,怎樣通過Python來顯示呢?
1.查詢所有數(shù)據(jù)庫
首先,我們查看本地數(shù)據(jù)庫中所包含的數(shù)據(jù)庫名稱,通過“show databases”語句。

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ù)庫代碼為:
conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306)
訪問root超級用戶,其密碼為“123456”,端口為“3306”,其結(jié)果如下:

如果不知道本地數(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ù)。

# 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ù)如下:(姓名 密碼 序號)'
  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é)果如圖所示:


        對應(yīng)的MySQL中的結(jié)果是一致的,下圖是對應(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é)果如下所示,插入教師表,包含字段:教師序號(id)、教師名稱(name)、教師性別(sex)。

插入數(shù)據(jù)也可以通過execute(sql)方法實現(xiàn),如:
cur.execute("insert into student values( 'yxz', '111111', '10')")
但插入的新數(shù)據(jù)通常是通過變量進(jìn)行賦值,而不是固定的,所以要對這條語句中的值做修改。我們可以做如下修改:

# 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
>>> 

同樣,對數(shù)據(jù)庫的增刪改插都可以進(jìn)行,請讀者自行閱讀。
推薦資料:python使用mysql數(shù)據(jù)庫 - 蟲師
后面我會結(jié)合Python爬蟲講述,如何將爬取的內(nèi)容存儲在數(shù)據(jù)庫中,如我CSDN的博客,爬取博客標(biāo)題、發(fā)布時間、閱讀量和評論數(shù)。

MySQL數(shù)據(jù)庫中結(jié)果如下圖所示:

最后希望文章對你有所幫助,如果文章中存在不足或錯誤的地方,還請海涵~還是那句話,挺享受現(xiàn)在的老師生活,不論科研、項目,還是教學(xué),很充實,加油!

相關(guān)文章

最新評論