日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

python mysql library popular_【过时】MySQLdb:Python 操作 MySQL 数据库

發布時間:2024/9/19 数据库 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python mysql library popular_【过时】MySQLdb:Python 操作 MySQL 数据库 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

NOTE(2017-11-18): MySQLdb 不支持 Python 3,而 Python 3 是主流,所以就沒有學習的必要了。

環境:MySQL 5.6.27, Ubuntu 15.10 64-bit

官方簡介

MySQLdb is an thread-compatible interface to the popular MySQL

database server that provides the Python database API.

安裝

通過 pip 安裝

$ apt-get install python-dev libmysqlclient-dev

$ pip install MySQL-python

通過 apt 安裝

$ sudo apt-get install python-mysqldb

模塊 _mysql

MySQLdb 安裝好后,有兩個模塊或方式可用。模塊 _mysql 提供的是類似于 MySQL C 接口的 API,而模塊 MySQLdb 在 _mysql 基礎上又做了進一步封裝,使之符合 Python 的數據庫 API 規范。推薦使用后者。

使用 _mysql 的例子:

import _mysql

import sys

try:

con = _mysql.connect('localhost', 'root', '******', 'test')

con.query('select version()')

result = con.use_result()

print 'MySQL version: %s' % result.fetch_row()[0]

except _mysql.Error, e:

print 'Error %d: %s' % (e.args[0], e.args[1])

sys.exit(1)

finally:

if con:

con.close()

改用 MySQLdb:

import MySQLdb as mdb

import sys

try:

con = mdb.connect('localhost', 'root', '******', 'test')

cur = con.cursor()

cur.execute('select version()')

ver = cur.fetchone()

print 'MySQL version: %s' % ver

except mdb.Error, e:

print 'Error %d: %s' % (e.args[0], e.args[1])

sys.exit(1)

finally:

if con:

con.close()

創建表,插入數據

# coding: utf-8

import MySQLdb as mdb

con = mdb.connect('localhost', 'root', '******', 'test')

with con:

cur = con.cursor()

cur.execute('drop table if exists writers')

cur.execute('create table writers(id int primary key auto_increment,\

name varchar(25)) default charset utf8')

cur.execute('insert into writers(name) values("Jack London")')

cur.execute('insert into writers(name) values("Honore de Balzac")')

cur.execute('insert into writers(name) values("Lion Feuchtwanger")')

cur.execute('insert into writers(name) values("Emile Zola")')

cur.execute('insert into writers(name) values("Truman Capote")')

cur.execute('insert into writers(name) values("曹雪芹")')

查詢

一次取回所有結果:fetchall

import MySQLdb as mdb

con = mdb.connect('localhost', 'root', '******', 'test')

with con:

cur = con.cursor()

cur.execute('select * from writers')

# 結果集 rows 為元組(tuple)的元組,每一個元組代表了表中的一行。

rows = cur.fetchall()

for row in rows:

print row

挨個取回結果:fetchone

import MySQLdb as mdb

con = mdb.connect('localhost', 'root', '******', 'test')

with con:

cur = con.cursor()

cur.execute('select * from writers')

for i in range(cur.rowcount):

row = cur.fetchone()

print row

使用字典 Cursor

import MySQLdb as mdb

con = mdb.connect('localhost', 'root', '******', 'test')

def test_dict_cursor():

with con:

cur = con.cursor(mdb.cursors.DictCursor) # 字典 cursor

cur.execute('select * from writers limit 4')

# rows 為字典的元組

rows = cur.fetchall()

for row in rows:

print row['id'], row['name'] # 通過列名訪問結果

打印列名

import MySQLdb as mdb

con = mdb.connect('localhost', 'root', '******', 'test')

with con:

cur = con.cursor()

cur.execute('select * from writers limit 4')

rows = cur.fetchall()

# 元組的元組,每一個元組對應一個結果列,元組的第一個元素為列名。

desc = cur.description

# 打印前兩個結果列的列名。

print '%s %3s' % (desc[0][0], desc[1][0])

for row in rows:

print '%2s %3s' % row

Prepared Statements

Prepared Statements 可以提高安全性和性能,特別是對于多次重復執行的查詢。Python 的數據庫 API 規范建議了 5 種不同的方式來構造 Prepared Statements,MySQLdb 只支持其中的一種,代碼類似于 ANSI printf 的格式化操作。

Prepared Statements 在 ORM 庫(比如 SQLAlchemy)中應該會有更完善的支持。

注(2016-01-10):

這里的 Prepared Statements 只是客戶端的模擬,跟 MySQL Server 的 Prepared Statements 是兩碼事,所以并不能提高性能或安全性。(詳見 C API Prepared Statements)

import MySQLdb as mdb

con = mdb.connect('localhost', 'root', '******', 'test')

with con:

cur = con.cursor()

cur.execute("update writers set name = %s where id = %s",

("Guy de Maupasant", "4"))

print "Number of rows updated:", cur.rowcount

事務

前面的例子一直使用 with 語句來管理鏈接 (connection) 對象,避免了 commit 的直接調用。

一旦 cursor 創建,一個事務也就開始,結束時必須調用 commit 或 rollback。commit 提交修改,rollback 回滾。如果結合 with 語句使用的話,commit 和 rollback 都將自動完成,因為 MySQLdb 的鏈接對象可以當作 context manager 使用。

# coding: utf-8

import MySQLdb as mdb

try:

con = mdb.connect('localhost', 'root', '******', 'test')

# Cursor 創建,事務開始。

cur = con.cursor()

cur.execute('drop table if exists writers')

# MyISAM doesn't support transaction.

cur.execute('create table writers(id int primary key auto_increment,\

name varchar(25)) engine=innodb')

cur.execute('insert into writers(name) values("Jack London")')

cur.execute('insert into writers(name) values("Honore de Balzac")')

cur.execute('insert into writers(name) values("Lion Feuchtwanger")')

cur.execute('insert into writers(name) values("Emile Zola")')

cur.execute('insert into writers(name) values("Truman Capote")')

# 顯式地調用 commit 來結束一個事務。

con.commit()

except mdb.Error, e:

# 異常發生時,調用 rollback 進行回滾。

if con:

con.rollback()

print "Error %d: %s" % (e.args[0], e.args[1])

sys.exit(1)

finally:

if con:

con.close()

Cursor 有必要 close 嗎?

原則上講,不需要顯式地調用 cursor 對象的 close 方法,因為當 cursor 對象生命期結束時,close 方法會被自動調用。源碼如下:

class BaseCursor(object):

def __del__(self):

self.close()

self.errorhandler = None

self._result = None

不過,還是建議主動調用 close,這樣至少代碼的行為更加明顯。

總結

以上是生活随笔為你收集整理的python mysql library popular_【过时】MySQLdb:Python 操作 MySQL 数据库的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。