1、安裝PostgreSQL模塊html
pip install psycopg2
有時候會失敗,多安裝2次就行了(我是第二次成功了)。python
2、數據庫鏈接接口mysql
因爲Python統一了數據庫鏈接的接口,因此psycopg2和 MySQLdb 在使用方式上是相似的:web
pymysql.Connect()參數說明
host(str): MySQL服務器地址
port(int): MySQL服務器端口號
user(str): 用戶名
password(str): 密碼
database(str): 數據庫名稱
connection對象支持的方法
cursor() 使用該鏈接建立並返回遊標
commit() 提交當前事務
rollback() 回滾當前事務
close() 關閉鏈接
cursor對象支持的方法
execute(op) 執行一個數據庫的查詢命令
fetchone() 取得結果集的下一行
fetchmany(size) 獲取結果集的下幾行
fetchall() 獲取結果集中的全部行
rowcount() 返回數據條數或影響行數
close() 關閉遊標對象
3、範例sql
MySql腳本數據庫
-- ---------------------------- -- Table structure for account -- ---------------------------- DROP TABLE IF EXISTS `account`; CREATE TABLE `account` ( `acctid` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `money` decimal(50, 0) NULL DEFAULT NULL ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of account -- ---------------------------- INSERT INTO `account` VALUES ('1', '張三', 50); INSERT INTO `account` VALUES ('2', '李四', 150);
Python程序服務器
# coding:utf8 import sys
import psycopg2 #PostgreSQL
class TransferMoney(object): def __init__(self, conn): self.conn = conn def check_acct_available(self, acctid): cursor = self.conn.cursor() try: sql = "select * from account where acctid='%s'" % acctid print("check_acct_available:" + sql) cursor.execute(sql) rs = cursor.fetchall() if len(rs) != 1: raise Exception("賬號%s不存在" % acctid) finally: cursor.close() def has_enough_money(self, acctid, money): cursor = self.conn.cursor() try: sql = "select * from account where acctid='%s' and money>%s" % ( acctid, money) print("has_enough_money:" + sql) cursor.execute(sql) rs = cursor.fetchall() if len(rs) != 1: raise Exception("賬號%s沒有足夠的金額" % acctid) finally: cursor.close() def reduce_money(self, acctid, money): cursor = self.conn.cursor() try: sql = "update account set money=money-%s where acctid='%s' " % ( money, acctid) print("reduce_money:" + sql) cursor.execute(sql) if cursor.rowcount != 1: raise Exception("賬號%s減款失敗" % acctid) finally: cursor.close() def add_money(self, acctid, money): cursor = self.conn.cursor() try: sql = "update account set money=money+%s where acctid='%s' " % ( money, acctid) print("add_money:" + sql) cursor.execute(sql) if cursor.rowcount != 1: raise Exception("賬號%s加款失敗" % acctid) finally: cursor.close() def transfer(self, source_acctid, target_acctid, money): try: self.check_acct_available(source_acctid) self.check_acct_available(target_acctid) self.has_enough_money(source_acctid, money) self.reduce_money(source_acctid, money) self.add_money(target_acctid, money) self.conn.commit() except Exception as e: self.conn.rollback() print("transfer出現異常:" + str(e)) raise e def main(): source_acctid = sys.argv[1] print("轉出賬號=" + source_acctid) target_acctid = sys.argv[2] print("轉入賬號=" + target_acctid) money = sys.argv[3] print("金額=" + money) # 鏈接數據庫 MySql #conn = pymysql.Connect( # host='localhost', # port=3306, # user='root', # passwd='root', # db='OtkDb', # charset='utf8')
tr_money = TransferMoney(conn) try: tr_money.transfer(source_acctid, target_acctid, money) except Exception as e: print("main出現異常:" + str(e)) finally: conn.close() if __name__ == '__main__': main()
4、運行效果post
PS H:\web\Python> & python h:\web\Python\01.MySql\db.py 1 2 50 轉出賬號=1 轉入賬號=2 金額=50 check_acct_available:select * from account where acctid='1' check_acct_available:select * from account where acctid='2' has_enough_money:select * from account where acctid='1' and money>50 reduce_money:update account set money=money-50 where acctid='1' add_money:update account set money=money+50 where acctid='2'
PS H:\web\Python> & python h:\web\Python\01.MySql\db.py 1 2 50 轉出賬號=1 轉入賬號=2 金額=50 check_acct_available:select * from account where acctid='1' check_acct_available:select * from account where acctid='2' has_enough_money:select * from account where acctid='1' and money>50 transfer出現異常:賬號1沒有足夠的金額 main出現異常:賬號1沒有足夠的金額
參考:fetch
https://www.cnblogs.com/Erick-L/p/7106816.htmlspa