2014-06-21 3 views
0

내 코드가 쿼리를 실행 한 다음 결과 집합의 각 행에 대해 해당 행의 값을 사용하여 다른 쿼리를 실행하려고합니다. MySQLdb.execute()에 매개 변수 값을 삽입하는 문제

import MySQLdb as mdb 
try: 
    con = mdb.connect('localhost', 'root', '', 'cccorder_uk'); 

    with con: 
     cur = con.cursor() 
     cur.execute("SELECT code, name, box_size, commodity_code, country_of_origin FROM cccorder_uk.stocks") 
     rows = cur.fetchall() 
     for row in rows: 
      # split the code and take colour and size 

      code = row[0].split('-') 
      product_code = code[0] 

      sql = """SELECT stock_groups.name FROM stock_groups_styles_map, stock_groups WHERE stock_groups_styles_map.style='%s'""" % (product_code,) 

      cur.execute(sql) 
      results = cur.fetchall() 
      print results 

except mdb.Error, e: 

    print "Error %d: %s" % (e.args[0],e.args[1]) 
    sys.exit(1) 

finally:  

    if con:  
     con.close() 

내가 results를 인쇄

나는 빈 튜플을 얻을,하지만 난 하드 코드 product_code는, 예를 sql = """SELECT stock_groups.name FROM stock_groups_styles_map, stock_groups WHERE stock_groups_styles_map.style='EP22'"""를 들어,이 결과를 반환하는 경우 내가 기대합니다.

왜 코드가 빈 튜플을 인쇄합니까?

+0

넣어 '인쇄 sql' 후 내부'cur.execute' 또는'인쇄 cur._executed' 그 후 그것을 게시하시기 바랍니다 – Korem

+0

' 전 stock_groups_styles_map FROM SELECT stock_groups.name는 \t \t \t \t 을 stock_groups WHERE stock_groups_styles_map.style = 'EP01'' – khinester

+0

때 하드 코드 당신에게 전자를 수행'product_code', 쿼리를 실행 하시겠습니까? 파이썬에서 MySQLdb를 사용하고 있습니까? 아니면 Workbench와 같은 다른 환경에서? – Air

답변

1

파이썬의 문자열 형식 연산자 %은 MySQL에 대한 args를 인용 할만큼 똑똑하지 않습니다. args를 MySQL에 정확하게 전달할 데이터베이스 execute 함수에 전달합니다.

예 :

cur.execute("SELECT stock_groups.name FROM stock_groups_styles_map, stock_groups WHERE stock_groups_styles_map.style=%s", product_code) 

참조 : How can I format strings to query with mysqldb in Python?

+0

그러나 OP 코드에서 그는 이미 – Korem

+0

@Korem : yes, * 변수가 문자열 일 경우 따옴표를 처리했습니다. 따옴표가없는 경우 * 및 *. 데이터베이스 커서는 파이썬에없는 추가 정보가 있기 때문에 어떤 것도 인용 할만큼 똑똑합니다. – johntellsall

+0

내가 말하고자하는 것은 그 특별한 경우에 그는 이미 인용을 처리했기 때문에 당신의 대답은 아마도 그 질문에 답을하지 않을 것입니다. 코멘트에 올린 쿼리를보십시오. 괜찮습니다. 물론 execute를 사용하는 것이 낫지 만 그게 문제는 아닙니다. – Korem