Python——使用psycopy2操作PostgreSQL

簡述:

Psycopg2與其他實現了DB API 2.0協議的其他數據庫用戶基本一致。當執行包含特殊字符的SQL語句的時候,傳遞數據用來填充查詢佔位符, 讓Psycopg執行正確的轉換(不再有SQL注入)


代碼:

# encoding: utf-8
__author__ = 'chenlong'

import psycopg2
from config import ConfigServer

class PGSQLdb:
    def __init__(self):
        self.tryconnect()

    def tryconnect(self):
        # 連接到數據庫
        self.con=psycopg2.connect(database = ConfigServer['pg_db'],
                     user = ConfigServer['pg_user'],
                     password = ConfigServer['pg_pass'],
                            host= ConfigServer['pg_host'],
                            port = ConfigServer['pg_port'])

        # 打開一個光標,用來執行數據庫操作
        self.cur=self.con.cursor()

    def tryexecute(self,sqlstr):
        # 執行命令
        self.cur.execute(sqlstr)
        # 使改變永久存入數據庫
        self.con.commit()


    def tryexecute2(self,sqlstr,data):
            # 傳遞數據用來填充查詢佔位符, 讓Psycopg執行正確的轉換(不再有SQL注入)
            # 第一個參數:包含佔位符的SQL語句,如:"INSERT INTO test (num, data) VALUES (%s, %s)"
            # 第二個參數:與佔位符對應的值,如: (100, "abc’def")
            self.cur.execute(sqlstr,data)
            self.con.commit()

    def tryclose(self):
        # 關閉光標
        self.cur.close()
        # 關閉連接
        self.con.close()


發佈了26 篇原創文章 · 獲贊 62 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章