2017-05-02 10 views
0

私は動的にクエリを構築し、psycopg2パッケージを使用して実行しようとしています。今、私はこのコードを実行すると、私はエラーkwargs psycopg2でクエリを構築する

cursor.execute(sql, **kwargs) 
TypeError: execute() got an unexpected keyword argument 'user_id' 

を取得

def execute(sql, **kwargs): 
    with closing(psycopg2.connect(dbname=config.instance().db_name, 
           user=config.instance().db_user, 
           password=config.instance().db_password, 
           host=config.instance().db_host, 
           port=config.instance().db_port)) as conn: 
     with closing(conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)) as cursor: 
     cursor.execute(sql, **kwargs) 
     return cursor.fetchall() 

:私が持っているクエリは次のようになります今私のクエリスクリプトでメソッドを実行

def get_employees_for_dept(dept_id): 
    sql = '''SELECT 
      emp.FirstName, 
      emp.LastName, 
      dep.DepartmentName 
     FROM Employee emp 
     JOIN Department dep 
     ON 
      dp.EmployeeID = emp.Id 
     WHERE 
      dp.Id = :dept_id'''; 
return query.execute(sql, dept_id=dept_id) 

以下のようになります。文字列の書式設定や文字列作成をせずに、この作業を行うにはどうすればよいですか?

答えて

0

あなたはパラメータのないリスト、execute methodに2番目のパラメータとしてタプルまたは辞書を渡す必要があります。

しかし、あなたはfun(sql, **kwargs)を行うときに、あなたが実際にアンロールコンテナ:SQLに値を注入について

def add_row(*args): # takes multiple arguments 
    cur.execute(""" 
    INSERT INTO my_table (id, value) 
    VALUES (%s, %s) 
    """, args) # args is a tuple 

my_args = (1, "some") 
add_row(*my_args) 
add_row(*(1, "some")) 
add_row(1, "some") 


def add_row(**kwargs): # takes multiple arguments 
    cur.execute(""" 
    INSERT INTO my_table (id, value) 
    VALUES (:a, :b) 
    """, kwargs) # kwargs is a dict 

my_kwargs = {"a":1, "b":"some"} 
add_row(**my_kwargs) 
add_row(**{"a":1, "b":"some"}) 
add_row(a=1, b="some") 

読むhere簡単:ここfun(sql, a=5, b="ten", ...)

は小さな一例です。 psycopg2はPython Database API Specificationを実装しているため、より詳しく見ていく必要があります。

+0

add_row(a = 1、b = "some")これは私のやり方とどのように違うのですか?値をハードコーディングする代わりに、関数が受け取ったものを渡しますか? –

+0

コードサンプルでは、​​ 'return query.execute(sql、{" dept_id ":dept_id})'と 'cursor.execute(sql、kwargs)'と書く必要があります。 – Rabash

関連する問題