Python學習筆記 - PostgreSQL的使用

來源:互聯網
上載者:User

標籤:方式   個數   root   python程式   使用者   學習   passwd   tps   nal   

一、安裝PostgreSQL模組

pip install psycopg2

有時候會失敗,多安裝2次就好了(我是第二次成功了)。

二、資料庫連接介面

由於Python統一了資料庫連接的介面,所以psycopg2和 MySQLdb 在使用方式上是類似的:

 
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()         關閉遊標對象
 

 

三、範例

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:utf8import 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 edef 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‘)
    # 串連資料庫PostgreSQL    conn = psycopg2.connect(      host=‘localhost‘,      port=5432,      user=‘postgres‘,      password=‘postgres‘,      database=‘OtkDb‘)
    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()
 

 四、運行效果

 
PS H:\web\Python> & python h:\web\Python\01.MySql\db.py 1 2 50轉出帳號=1轉入帳號=2金額=50check_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>50reduce_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金額=50check_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>50transfer出現異常:帳號1沒有足夠的金額main出現異常:帳號1沒有足夠的金額
 

 

參考:

https://www.cnblogs.com/Erick-L/p/7106816.html

Python學習筆記 - PostgreSQL的使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.