国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python數據庫編程

2019-11-06 08:08:23
字體:
來源:轉載
供稿:網友

轉自:http://lizhenliang.blog.51cto.com/7876557/1874283

Python的MySQL數據庫操作模塊叫MySQLdb,需要額外的安裝下。

通過pip工具安裝:pip install MySQLdb

MySQLdb模塊,我們主要就用到連接數據庫的方法MySQLdb.Connect(),連接上數據庫后,再使用一些方法做相應的操作。

MySQLdb.Connect(parameters...)方法提供了以下一些常用的參數:

參數

描述

host數據庫地址
user數據庫用戶名,
passwd數據庫密碼,默認為空
db數據庫庫名,沒有默認庫
port數據庫端口,默認3306
connect_timeout連接超時時間,秒為單位
use_unicode結果以unicode字符串返回
charset插入數據庫編碼

連接對象返回的connect()函數:

commit()提交事務。對支持事務的數據庫和表,如果提交修改操作,不適用這個方法,則不會寫到數據庫中
rollback()事務回滾。對支持事務的數據庫和表,如果執行此方法,則回滾當前事務。在沒有commit()前提下。
cursor([cursorclass])創建一個游標對象。所有的sql語句的執行都要在游標對象下進行。MySQL本身不支持游標,MySQLdb模塊對其游標進行了仿真。

游標對象也提供了幾種方法:

close()關閉游標
execute(sql)執行sql語句
excutemany(sql)執行多條sql語句
fetchone()從執行結果中取第一條記錄
fetchmany(n)從執行結果中取n條記錄
fetchall()從執行結果中取所有記錄
scroll(self, value, mode='relative')游標滾動

1 數據庫增刪改查

1.1 在test庫創建一張user表,并添加一條記錄

>>> conn = MySQLdb.Connect(host='192.168.1.244',user='root',passwd='QHyCTajI',db='test',charset='utf8')>>> cursor = conn.cursor()>>> sql = "create table user(id int,name varchar(30),passWord varchar(30))">>> cursor.execute(sql)   # 返回的數字是影響的行數0L    >>> sql = "insert into user(id,name,password) values('1','xiaoming','123456')">>> cursor.execute(sql)1L>>> conn.commit()  # 提交事務,寫入到數據庫>>> cursor.execute('show tables')  # 查看創建的表1L>>> cursor.fetchall()  # 返回上一個游標執行的所有結果,默認是以元組形式返回((u'user',),)>>> cursor.execute('select * from user')           1L>>> cursor.fetchall()((1L, u'xiaoming', u'123456'),)1.2 插入多條數據

>>> sql = 'insert into user(id,name,password) values(%s,%s,%s)'>>> args = [('2','zhangsan','123456'), ('3','lisi','123456'),('4','wangwu','123456')] >>> cursor.executemany(sql, args)3L>>> conn.commit()>>> sql = 'select * from user'>>> cursor.execute(sql)4L>>> cursor.fetchall()((1L, u'xiaoming', u'123456'), (2L, u'zhangsan', u'123456'), (3L, u'lisi', u'123456'), (4L, u'wangwu', u'123456'))args變量是一個包含多元組的列表,每個元組對應著每條記錄。當查詢多條記錄時,使用此方法,可有效提高插入效率。

1.3 刪除用戶名xiaoming的記錄

>>> sql = 'delete from user where name="xiaoming"'>>> cursor.execute(sql)                           1L>>> conn.commit()>>> sql = 'select * from user'                   >>> cursor.execute(sql)       3L>>> cursor.fetchall()         ((2L, u'zhangsan', u'123456'), (3L, u'lisi', u'123456'), (4L, u'wangwu', u'123456'))

1.4 查詢記錄

>>> sql = 'select * from user' >>> cursor.execute(sql)         3L>>> cursor.fetchone()   # 獲取第一條記錄(2L, u'zhangsan', u'123456')>>> sql = 'select * from user' >>> cursor.execute(sql)         3L>>> cursor.fetchmany(2) # 獲取兩條記錄((2L, u'zhangsan', u'123456'), (3L, u'lisi', u'123456'))

1.4 以字典形式返回結果

默認顯示是元組形式,要想返回字典形式,使得更易處理,就用到cursor([cursorclass])中的cusorclass參數。

傳入MySQLdb.cursors.DictCursor類:

>>> cursor = conn.cursor(MySQLdb.cursors.DictCursor)>>> sql = 'select * from user'>>> cursor.execute(sql)3L>>> cursor.fetchall()({'password': u'123456', 'id': 2L, 'name': u'zhangsan'}, {'password': u'123456', 'id': 3L, 'name': u'lisi'}, {'password': u'123456', 'id': 4L, 'name': u'wangwu'})

2 遍歷查詢結果

#!/usr/bin/env python# -*- coding: utf-8 -*-import MySQLdbtry:    conn = MySQLdb.Connect(host='127.0.0.1', port=3306, user='root', passwd='123456', connect_timeout=3, charset='utf8')    cursor = conn.cursor()    sql = "select * from user"    cursor.execute(sql)    for i in cursor.fetchall():        PRint iexcept Exception, e:    print ("Connection Error: " + str(e))finally:    conn.close()     # python test.py(2L, u'zhangsan', u'123456')(3L, u'lisi', u'123456')(4L, u'wangwu', u'123456')


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 和龙市| 昔阳县| 华阴市| 东乡族自治县| 紫云| 海伦市| 应城市| 微山县| 雅江县| 天柱县| 江阴市| 琼海市| 镇原县| 怀柔区| 山丹县| 涞水县| 洮南市| 平遥县| 洪洞县| 茌平县| 托克托县| 宝山区| 伊通| 电白县| 江阴市| 临桂县| 白沙| 黄梅县| 特克斯县| 平远县| 双鸭山市| 怀仁县| 渝北区| 绥棱县| 四川省| 武定县| 广安市| 惠来县| 子长县| 松原市| 长葛市|