2016-06-27 2 views
1

이 실행 문 또는 내가 전달하는 목록에 문제가 있습니다.매개 변수가있는 MySQL 테이블을 만들 때 TypeError가 발생했습니다.

나는 점점 계속 :

Traceback (most recent call last): 
    File "/Users/Hardway/test_package/sqltest5.py", line 12, in <module> 
    cur.execute(create_table, ('userid', 'age_of_account', 'number_of_friends', 'DA_MA', 'user_quality'))  
    File "/Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.11-intel.egg/MySQLdb/cursors.py", line 184, in execute 
    query = query % db.literal(args) 
TypeError: not all arguments converted during string formatting 

지금 해봤 다 (튜플, 문자열의 PARAM 변수 등 3 종류의 강제)와 약간의 도움을 사용할 수 있습니다. 내가 뭘 놓치고 있니?

import MySQLdb as MS 
db1 = MS.connect(host="localhost", user="yosef",passwd="yosef", db ='test2') 

cur = db1.cursor() 

header = ('userid', 'age_of_account', 'number_of_friends', 'DA_MA', 'user_quality') 
drop_table = "DROP TABLE IF EXISTS Users" 
create_table = """Create table Users ({0} int, {1} int, {2} int, {3} float, {4} varchar(10))""" 

try: 
    cur.execute(drop_table) 
    cur.execute(create_table, header,)  

    db1.commit() 

except MS.Error, e: 
    print "That failed" 
    print e.args[0], e.args[1] 
    db1.rollback() 

finally: 
    db1.close() 
+0

그래서 이미 시도해 보았습니다 : create_table = "테이블 사용자 ({1} int, {2} int, {3 float, {4} varchar (10))"테이블 사용자를 만듭니다. ','age_of_account ','number_of_friends ','DA_MA ','user_quality ')? –

+1

예. 컴퓨터 앞에 앉아서 테스트하자마자. 지금 나는 아이를 낳고있어. 이 커뮤니티의 놀라운 점에 대해 감사 드리지는 못하지만 코드를 테스트 할 수 없게되었습니다. :) – SAR622

답변

1

쿼리 매개 변수로 열 이름을 cursor.execute()에 전달할 수 없습니다. 당신은 쿼리로 보간하는 문자열 formatting를 사용해야합니다 :

create_table = ("CREATE TABLE Users ({} INT, {} INT, {} INT, {} FLOAT," 
       "{} VARCHAR(10))".format(*header)) 
cur.execute(create_table) 

은 물론, 당신은 header 사용자 입력이 포함되지 않도록 각별히주의해야합니다.

1

MySQLCursor.execute에 전달할 수 있지만 열 이름은 전달할 수 없습니다. 그래서, str.format를 사용 str.format와 함께 사용할 때 expand the tuple*를 사용할 필요가

create_table = "Create table Users ({0} int, {1} int, {2} int, {3} float, {4} varchar(10))".format(*header) 
cur.execute(create_table) 

참고.

관련 문제