Python學習系列(七)( 數據庫編程)

一,MySQL-Python插件

    Python裏操作MySQL數據庫,需要Python下安裝訪問MySQL數據庫接口API包即插件,從而使得Python2.7能訪問操作MySQL數據庫。MySQL軟件可以去官網下載:http://www.mysql.com/

二,訪問MySQL數據庫

    1,連接數據庫mysql

       基本格式:connect ([host=]'ip',[user=]'user',[passwd=]'password',[db=]'dbname')

    2,數據庫的基本操作

     1)create創建表

import MySQLdb
#connect to a database 'test'
conn=MySQLdb.connect(host='localhost',user='root',passwd='zbc123',db='test')
cursor=conn.cursor()
#create a table
cursor.execute('create table \
test(ID int primary key auto_increment,Name char(25))')
#Closing database
cursor.close()
conn.close()

     2)fetchall訪問:

import MySQLdb
#connect to a database 'test'
conn=MySQLdb.connect(host='localhost',user='root',passwd='zbc123',db='test')
cursor=conn.cursor()
#fetch datas
n=cursor.execute('select * from test;')
r=cursor.fetchall()
print n,r
#Closing database
cursor.close()
conn.close()

>>> ================================ RESTART ================================
>>> 
3 ((4L, 'zhangbc'), (5L, 'lis08'), (6L, 'wangw'))
>>>

      在Mysql5.6環境下運行:

wKioL1QCxY2yVEa7AAGfJZhmYtw943.jpg

      3)insert向表中插入數據:

import MySQLdb
#connect to a database 'test'
conn=MySQLdb.connect(host='localhost',user='root',passwd='zbc123',db='test')
cursor=conn.cursor()
#insert data into table 'test'
mysql='''insert into test(id,sname) values(4,'zhanghua')'''
cursor.execute(mysql)
conn.commit()#below mysql5.0 needed
#fetch datas
n=cursor.execute('select * from test;')
r=cursor.fetchall()
print n,r
#Closing database
cursor.close()
conn.close()

>>> ================================ RESTART ================================
>>>
4 ((1L, 'zhangbc'), (2L, 'lis'), (3L, 'wangw'), (4L, 'zhanghua'))

      注意:一定要寫上conn.commit();事物不提交,將回滾。比較:

wKioL1QCx32TZku4AASrbvOM2cI869.jpg

wKiom1QCxoDQgmMOAATzUDZNdcU530.jpg

     4)update修改表中數據:

import MySQLdb
#connect to a database 'test'
conn=MySQLdb.connect(host='localhost',user='root',passwd='zbc123',db='test')
cursor=conn.cursor()
#update data of the table 'test'
mysql='''update test set sname='Lisi08' where id=2'''
cursor.execute(mysql)
conn.commit()#below mysql5.0 needed
#fetch datas
n=cursor.execute('select * from test;')
r=cursor.fetchall()
print n,r
#Closing database
cursor.close()
conn.close()

>>> ================================ RESTART ================================
>>>
4 ((1L, 'zhangbc'), (2L, 'Lisi08'), (3L, 'wangw'), (4L, 'zhanghua'))

     5)delete刪除表中數據:

import MySQLdb
#connect to a database 'test'
conn=MySQLdb.connect(host='localhost',user='root',passwd='zbc123',db='test')
cursor=conn.cursor()
#delete data of the table 'test'
mysql='''delete from test where id=4'''
cursor.execute(mysql)
conn.commit()#below mysql5.0 needed
#fetch datas
n=cursor.execute('select * from test;')
r=cursor.fetchall()
print n,r
#Closing database
cursor.close()
conn.close()

>>> ================================ RESTART ================================
>>>
3 ((1L, 'zhangbc'), (2L, 'Lisi08'), (3L, 'wangw'))

     6)關於select及其遍歷:

      i)使用元組tuplefetchone結合

import MySQLdb
#connect to a database 'test'
conn=MySQLdb.connect(host='localhost',user='root',passwd='zbc123',db='test')
cursor=conn.cursor()
#fetch datas
cursor.execute('select * from test;')
#獲得結果集的記錄
numrows=int(cursor.rowcount)
#循環,取行數據
for i in range(numrows):
    row=cursor.fetchone()
    print row[0],row[1]
#Closing database
cursor.close()
conn.close()

>>> ================================ RESTART ================================
>>> 
4 zhangbc
5 lis08
6 wangw

      ii)使用字典cursor

#-*- coding:UTF-8 -*-
import MySQLdb as mdb
#connect to a database 'test'
conn=mdb.connect(host='localhost',user='root',passwd='zbc123',db='test')
with conn:
    #獲取連接上的字典cursor,每一個cursor其實都是cursor的子類
    cur=conn.cursor(mdb.cursors.DictCursor)
#fetch datas
cur.execute('select * from test;')
#獲得結果集
rows=cur.fetchall()
#循環,取行數據
for row in rows:
    print '%s %s'%(row['ID'],row['Name'])
#Closing database
cur.close()
conn.close()

>>> ================================ RESTART ================================
>>> 
4 zhangbc
5 lis08
6 wangw

       iii)獲取單個表的字段名及其信息

#-*- coding:UTF-8 -*-
import MySQLdb as mdb
#connect to a database 'test'
conn=mdb.connect(host='localhost',user='root',passwd='zbc123',db='test')
with conn:
    #獲取連接上的字典cursor,每一個cursor其實都是cursor的子類
    cur=conn.cursor()
#fetch datas
cur.execute('select * from test;')
#獲得結果集
rows=cur.fetchall()
#獲得鏈接對象的描述信息
desc=cur.description
print 'cur.description:',desc
#打印表頭
print '%2s %3s'%(desc[0][0],desc[1][0])
#循環,取行數據
for row in rows:
    print '%2s %3s'%row
#Closing database
cur.close()
conn.close()

>>> ================================ RESTART ================================
>>> 
cur.description: (('ID', 3, 1, 11, 11, 0, 0), ('Name', 254, 7, 25, 25, 0, 1))
ID Name
 4 zhangbc
 5 lis08
 6 wangw

三,小結

     本文主要介紹了Python下如何訪問並操數據庫的基本知識,如:如何連接數據庫,如何執行執行SQL語句等等。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章