python db-api使用流程:
一、python查詢mysql使用 fetchone() 方法獲取單條資料, 使用fetchall() 方法獲取多條資料。
fetchone(): 該方法獲取下乙個查詢結果集。結果集是乙個物件
fetchall():接收全部的返回結果行.
rowcount: 這是乙個唯讀屬性,並返回執行execute()方法後影響的行數。
二、事務機制可以確保資料一致性。
事務應該具有4個屬性:原子性、一致性、隔離性、永續性。這四個屬性通常稱為acid特性。
原子性(atomicity)。乙個事務是乙個不可分割的工作單位,事務中包括的諸操作要麼都做,要麼都不做。
一致性(consistency)。事務必須是使資料庫從乙個一致性狀態變到另乙個一致性狀態。一致性與原子性是密切相關的。
隔離性(isolation)。乙個事務的執行不能被其他事務干擾。即乙個事務內部的操作及使用的資料對併發的其他事務是隔離的,併發執行的各個事務之間不能互相干擾。
永續性(durability)。持續性也稱永久性(permanence),指乙個事務一旦提交,它對資料庫中資料的改變就應該是永久性的。接下來的其他操作或故障不應該對其有任何影響。
三、**塊:
資料庫使用通用**,例如:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import mysqldb
# 開啟資料庫連線
db = mysqldb.connect("localhost","root","123456","testdb" )
# 示例1:使用cursor()方法獲取操作游標
cursor = db.cursor()
# 使用execute方法執行sql語句
cursor.execute("select version()")
# 使用 fetchone() 方法獲取一條資料庫。
data = cursor.fetchone()
"database version : %s " % data
# 示例2:如果資料表已經存在使用 execute() 方法刪除表。
cursor.execute("drop table if exists employee")
# 建立資料表sql語句
sql = """create table employee (
first_name char(20) not null,
last_name char(20),
age int,
*** char(1),
income float )"""
cursor.execute(sql)
# 示例3:sql 插入語句
sql = """insert into employee(first_name,
last_name, age, ***, income)
values ('mac', 'mohan', 20, 'm', 2000)"""
sql2 = """insert into employee(first_name,
last_name, age, ***, income)
values ('windows', 'mohan2', 20, 'm', 4000)"""
try:
# 執行sql語句
cursor.execute(sql)
cursor.execute(sql2)
# 提交到資料庫執行
db.commit()
except:
# rollback in case there is any error
# 示例4:sql 查詢語句
sql = "select * from employee \
where income > '%d'" % (1000)
try:
# 執行sql語句
cursor.execute(sql)
# 獲取所有記錄列表
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
*** = row[3]
income = row[4]
# 列印結果
"fname=%s,lname=%s,age=%d,***=%s,income=%d" % \
(fname, lname, age, ***, income )
except:
"error: unable to fecth data"
# 示例5:sql 更新語句
sql = "update employee set age = age + 1 where *** = '%c'" % ('m')
try:
# 執行sql語句
cursor.execute(sql)
# 提交到資料庫執行
db.commit()
except:
# 發生錯誤時回滾
db.rollback()
#示例6: sql 刪除語句
sql = "delete from employee where age > '%d'" % (20)
try:
# 執行sql語句
cursor.execute(sql)
# 提交修改
db.commit()
except:
# 發生錯誤時回滾
db.rollback()
# 關閉資料庫連線
db.close()
python MysqlDb模組使用
python呼叫mysql資料庫通常通過mysqldb模組,簡單說下如何呼叫 1.安裝驅動 目前有兩個mysql的驅動,我們可以選擇其中乙個進行安裝 1.mysql python 是封裝了mysql c驅動的python驅動 2.mysql connector python 是mysql官方的純py...
python MySQLdb學習筆記
mysqldb庫是python訪問mysql的連線庫,最近專案中需要使用,將學習使用所得整理如下。mysqldb windows下執行需要 libmysql.dll libmmd.dll 和 libguide40.dll 可以放在sitepackage下也可以在windows system32 學習...
python MySQLdb連線mysql失敗問題
mysql exceptions.operationalerror 2002,can t connect to local mysql 在很多種情況下,如果配置檔案沒有出錯的話,將機器重啟,確認關閉防火牆,確定啟動了mysql即可。網上很不錯講解 最近了解了一下django,資料庫選用了mysql,...