Python 數據庫操作 -- Mysql 數據庫
Python DB API
價值
Python訪問數據庫的統一接口規範,開發者不必再去針對不同數據庫實現不同API
官網
https://www.python.org/dev/peps/pep-0249/
內容
使用流程
開發環境搭建
環境
Python代碼開發(Sublime Text3 / Notepad ++)
Python客戶端 AND Python-MySQL connector
Mysql服務器(Mysql5.7 AND Navicat)
安裝Python-MySQL connector及遇到的問題
安裝
win cmd 中輸入 easy_install MySQL-python 或者 pip install MySQL-python
Linux apt-get install python-dev 或者 yum install python-devel
最笨的方法,到http://www.cr173.com/soft/22957.html這裏下載了MySQL-python.rar安裝包進行安裝。
問題
Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat)
http://www.cnblogs.com/lemonlemontree/p/6921333.html
Cannot open include file: ‘config-win.h‘: No such file or directory
http://www.cnblogs.com/dadadechengzi/p/6131799.html
site.cfg需要下載MySQL-python的源代碼包
導入Python-MySQL完成
>>> import MySQLdb
>>> print MySQLdb
<module ‘MySQLdb‘ from ‘C:\Python27\lib\site-packages\mysql_python-1.2.5-py2.7-win-amd64.egg\MySQLdb\__init__.pyc‘>
數據庫連接對象--connection
作用
建立Python客戶端與數據庫的網絡連接
創建方法
實例名=Mysqldb.connect(參數)
host--字符串--mysql服務器地址
port--數字--mysql服務器端口號
user--字符串--用戶名
passwd--字符串--密碼
db--字符串--數據庫名
charset--字符串--連接編碼
實例方法
cursor()--使用該鏈接創建並返回遊標
commit()--提交當前事務
rollback()--回滾當前事務
close()--關閉連接
數據庫遊標對象--cursor
作用
用於執行查詢和獲取結果
實例方法
execute(op[,args])--執行一個數據庫查詢和命令
fetchone()--獲取下一行數據
fetchmany(size)--獲取下size行數據
fetchall()--獲取剩下的所有行(可直接使用for xx in cursor實例 來對cursor實例進行叠代)
rowcount--最近一次execute返回數據的行數或影響的行數,請註意,它是屬性。
rownumber--下一次使用fetchxxx時的index
close()--關閉遊標
Python之Select查詢操作
理念
實例:
1 >>> import MySQLdb 2 3 >>> test_conn=MySQLdb.Connect(host=‘127.0.0.1‘,port=3306,user=‘yc‘,passwd=‘Yc_123456‘,db=‘st‘,charset=‘utf8‘) 4 5 >>> sql = "select * from student" 6 7 >>> test_cursor=test_conn.cursor() 8 9 >>> test_cursor.execute(sql) 10 11 6L 12 13 >>> test_cursor 14 15 <MySQLdb.cursors.Cursor object at 0x0000000002EB7710> 16 17 >>> test_rs=test_cursor.fetchall() 18 19 >>> for row in test_rs: 20 21 ... print row 22 23 ... 24 25 (u‘201215121‘, u‘\u674e\u52c7‘, u‘\u7537‘, 21, u‘CS‘) 26 27 (u‘201215122‘, u‘\u5218\u6668‘, u‘\u5973‘, 23, u‘CS‘) 28 29 (u‘201215123‘, u‘\u738b\u654f‘, u‘\u5973‘, 19, u‘MA‘) 30 31 (u‘201215125‘, u‘\u5f20\u7acb‘, u‘\u7537‘, 20, u‘IS‘) 32 33 (u‘201215126‘, u‘\u5f20\u6210\u6c11‘, u‘\u7537‘, 19, u‘CS‘) 34 35 (u‘201215128‘, u‘\u9648\u51ac‘, u‘\u7537‘, 19, u‘IS‘) 36 37 >>> for row in test_cursor: 38 39 ... print row 40 41 ... 42 43 (u‘201215121‘, u‘\u674e\u52c7‘, u‘\u7537‘, 21, u‘CS‘) 44 45 (u‘201215122‘, u‘\u5218\u6668‘, u‘\u5973‘, 23, u‘CS‘) 46 47 (u‘201215123‘, u‘\u738b\u654f‘, u‘\u5973‘, 19, u‘MA‘) 48 49 (u‘201215125‘, u‘\u5f20\u7acb‘, u‘\u7537‘, 20, u‘IS‘) 50 51 (u‘201215126‘, u‘\u5f20\u6210\u6c11‘, u‘\u7537‘, 19, u‘CS‘) 52 53 (u‘201215128‘, u‘\u9648\u51ac‘, u‘\u7537‘, 19, u‘IS‘) 54 55 >>> test_cursor.fetchall() 56 57 () 58 59 >>> test_cursor.rowcount 60 61 6L 62 63 >>> dir(test_cursor) 64 65 [‘DataError‘, ‘DatabaseError‘, ‘Error‘, ‘IntegrityError‘, ‘InterfaceError‘, ‘InternalError‘, ‘MySQLError‘, ‘NotSupportedError‘, ‘OperationalError‘, ‘ProgrammingError‘, ‘Warning‘, ‘__class__‘, ‘__del__‘, ‘__delattr__‘, ‘__dict__‘, ‘__doc__‘, ‘__format__‘, ‘__getattribute__‘, ‘__hash__‘, ‘__init__‘, ‘__iter__‘, ‘__module__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘__weakref__‘, ‘_check_executed‘, ‘_defer_warnings‘, ‘_do_get_result‘, ‘_do_query‘, ‘_executed‘, ‘_fetch_row‘, ‘_fetch_type‘, ‘_get_db‘, ‘_get_result‘, ‘_info‘, ‘_last_executed‘, ‘_post_get_result‘, ‘_query‘, ‘_result‘, ‘_rows‘, ‘_warning_check‘, ‘_warnings‘, ‘arraysize‘, ‘callproc‘, ‘close‘, ‘connection‘, ‘description‘, ‘description_flags‘, ‘errorhandler‘, ‘execute‘, ‘executemany‘, ‘fetchall‘, ‘fetchmany‘, ‘fetchone‘, ‘lastrowid‘, ‘messages‘, ‘nextset‘, ‘rowcount‘, ‘rownumber‘, ‘scroll‘, ‘setinputsizes‘, ‘setoutputsizes‘] 66 67 >>> test_cursor.rownumber 68 69 6 70 71 >>> test_cursor.rownumber=0 72 73 >>> test_cursor.fetchone() 74 75 (u‘201215121‘, u‘\u674e\u52c7‘, u‘\u7537‘, 21, u‘CS‘) 76 77 >>> test_cursor.close() 78 79 >>> test_conn.close()Python之Select查詢簡單舉例
Python之insert/update/delete更新操作&事務使用
理念
Python之事務的使用
1.關閉自動提交:設置connection.autocommit(False)
2.正常提交事務:connection.commit()
3.異常回滾事務:connection.rollback()
實例
1 >>> import MySQLdb 2 3 >>> test_conn=MySQLdb.Connect(host=‘127.0.0.1‘,port=3306,user=‘yc‘,passwd=‘Yc_123456‘,db=‘st‘,charset=‘utf8‘) 4 5 >>> insert_sql="insert into student(Sno,Sname,Ssex,Sage,Sdept) values(201215130,‘王曉東‘,‘男‘,18,‘CS‘)" 6 7 >>> update_sql="update student set Ssex=‘女‘ where Sno=201215130" 8 9 >>> test_conn.autocommit(False) 10 11 >>> test_cursor=test_conn.cursor() 12 13 >>> try: 14 15 ... test_cursor.execute(insert_sql) 16 17 ... test_cursor.execute(update_sql) 18 19 ... test_conn.commit() 20 21 ... except Exception as e: 22 23 ... print e 24 25 ... test_conn.rollback() 26 27 ... 28 29 1L 30 31 1L 32 33 >>> test_cursor.close() 34 35 >>> test_conn.close()Python之更新語句簡單舉例
註:
(1062, "Duplicate entry ‘201215130‘ for key ‘PRIMARY‘")
明明數據庫中沒有,但是爆了這個錯,是因為crusor中已經有了‘201215130‘這個ID的記錄,所以需要初始化cursor實例(先close(),在重新賦值)
實例--銀行轉帳
create table account (
acctid INT(11) PRIMARY KEY COMMENT ‘賬戶ID‘,
money NUMERIC(11,2) DEFAULT 0.00 COMMENT ‘余額‘
) ENGINE = INNODB DEFAULT CHARSET = utf8;
引擎選擇--INNODB支持事務,MyISAM不支持事務
1 # -*- coding:utf-8 -*- 2 3 # 代碼編寫思路:先抽象後具體;先寫框架,後寫實現。 4 # 1.獲得源帳號、目標賬號、轉賬金額 5 # 2.連接數據庫 6 # 3.開始事務 7 # 4.提交或回滾 8 # ********************* 9 # 下列動作可封裝到一個類中 10 # 3.1檢查源帳號是否可用 11 # 3.2檢查目標賬號是否可用 12 # 3.3檢查源帳號是否有足夠的錢 13 # 3.4源帳號扣款 14 # 3.5目標賬號加錢 15 16 17 import MySQLdb 18 19 # parameters define here 20 src_id = input(‘input src account id >‘) 21 des_id = input(‘input des account id >‘) 22 money = input(‘money number >‘) 23 24 class MyException(Exception): 25 def __init__(self,message): 26 Exception.__init__(self) 27 self.message=message 28 29 class TransferMoney(object): 30 def __init__(self,db_connect_instance): 31 self.__db_conn=db_connect_instance 32 33 def check_account_available(self,account_id): 34 print "檢查賬戶%s是否可用..." % account_id 35 __sql="select * from account where acctid=%s" % account_id 36 __curosr = self.__db_conn.cursor() 37 __curosr.execute(__sql) 38 #print "rowcount-->%s" % __curosr.rowcount 39 if __curosr.rowcount!=1: 40 print "賬戶%s不可用"% account_id 41 raise MyException("賬戶%s不可用"% account_id) 42 print "賬戶%s可用" % account_id 43 __curosr.close() 44 45 def check_enough_money(self,account_id, money): 46 print "檢查賬戶%s余額是否足夠..." % account_id 47 __sql="select * from account where acctid=%s and money>=%s" % (account_id, money) 48 __curosr = self.__db_conn.cursor() 49 __curosr.execute(__sql) 50 #print "rowcount-->%s" % __curosr.rowcount 51 if __curosr.rowcount!=1: 52 print "賬戶%s余額不足"% account_id 53 raise MyException("賬戶%s余額不足"% account_id) 54 print "賬戶%s余額充足" % account_id 55 __curosr.close() 56 57 def reduce_money(self,account_id, money): 58 print "賬戶%s開始扣款..." % account_id 59 __sql="update account set money=money-%s where acctid=%s" % (money, account_id) 60 __curosr = self.__db_conn.cursor() 61 __curosr.execute(__sql) 62 #print "rowcount-->%s" % __curosr.rowcount 63 if __curosr.rowcount!=1: 64 print "賬戶%s扣款失敗"% account_id 65 raise MyException("賬戶%s扣款失敗"% account_id) 66 print "賬戶%s扣款成功" % account_id 67 __curosr.close() 68 69 def add_money(self,account_id, money): 70 print "賬戶%s開始加錢..." % account_id 71 __sql="update account set money=money+%s where acctid=%s" % (money, account_id) 72 __curosr = self.__db_conn.cursor() 73 __curosr.execute(__sql) 74 #print "rowcount-->%s" % __curosr.rowcount 75 if __curosr.rowcount!=1: 76 print "賬戶%s加錢失敗"% account_id 77 raise MyException("賬戶%s加錢失敗"% account_id) 78 print "賬戶%s加錢成功" % account_id 79 __curosr.close() 80 81 def main(): 82 st_conn = MySQLdb.Connect(host=‘127.0.0.1‘,port=3306,user=‘yc‘,passwd=‘Yc_123456‘,db=‘st‘,charset=‘utf8‘) 83 84 transfer_money = TransferMoney(st_conn) 85 86 try: 87 transfer_money.check_account_available(src_id) 88 transfer_money.check_account_available(des_id) 89 transfer_money.check_enough_money(src_id,money) 90 transfer_money.reduce_money(src_id,money) 91 transfer_money.add_money(des_id,money) 92 st_conn.commit() 93 print "從帳號%s轉%s元到帳號%s成功!!!" % (src_id, money, des_id) 94 except Exception as e: 95 print "從帳號%s轉%s元到帳號%s失敗!!!" % (src_id, money, des_id) 96 print e.message 97 st_conn.rollback() 98 99 st_conn.close() 100 101 main()Python代碼實現銀行轉帳
Python 數據庫操作 -- Mysql 數據庫