mysqldb : 쿼리에 전달 된 큰 따옴표가 전달되었습니다
-
13-12-2019 - |
문제
나는 mysqldb로 화를 내고있다!나는 공식적인 문서를 정확히 다음과 같이 팔로졌지만 코드가 오류가 있습니다.
DB_TABLE = "test"
cursor.execute("SELECT MAX(id) AS maxid FROM " + DB_TABLE)
print "***"
cursor.execute("SELECT MAX(id) AS maxid FROM %s" , (DB_TABLE,))
.
오류가 발생했습니다 :
Traceback (most recent call last):
File "dbscript.py", line 49, in <module>
cursor.execute("SELECT MAX(id) AS maxid FROM %s" , (DB_TABLE,))
File "build/bdist.macosx-10.7-intel/egg/MySQLdb/cursors.py", line 174, in execute
File "build/bdist.macosx-10.7-intel/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test'' at line 1")
.
분명히 어떤 인용문에 문제가 있습니다.내 명령은 이와 같은 선을 mysql에 보내는 것처럼 보입니다 :
SELECT MAX(id) AS maxid FROM ''test''
.
어떻게 한 번씩 이중 따옴표를 변경할 수 있습니까?
i'v는 다음을 시도했습니다.
DB_TABLE = 'test'
cursor.execute("SELECT MAX(id) AS maxid FROM %s" , [DB_TABLE])
cursor.execute("SELECT MAX(id) AS maxid FROM %s" , ("test",))
.
그러나 아무것도 작동하지 않습니다 : (
해결책
cursor.execute("SELECT MAX(id) AS maxid FROM %s" , ("test",))
.
및 유사한 진술에서 cursor.execute
는 SQL 매개 변수를 % s로 대체합니다.
필요한 것은이
와 같습니다.sql = "SELECT MAX(id) AS maxid FROM %s" % ("test", )
cursor.execute(sql)
. 다른 팁
테이블 이름을 매개 변수화 할 수 없으므로 스스로를 살균하고 쿼리에서 문자열 대체를 사용해야합니다.
sanitize 여러 매개 변수가있는 쿼리에서 테이블 이름을
query = "SELECT * FROM %s WHERE columnName = %s" % (tableName,'%s')
print(query)
.
이 시점에서 쿼리가 다음과 같이 표시됩니다.
SELECT * FROM tableName WHERE columName = %s
.
커서를 구성한 후에는 매개 변수화 된 조건을 사용하십시오.
cursor.execute(query,(columnValue,))
.
MySQL이 읽을 실제 쿼리는 다음과 같습니다.
SELECT * FROM tableName WHERE columnName = columnValue
.
이를 살균하지 않고 테이블 이름을 전달하려고하면 구문 오류가 발생합니다.
제휴하지 않습니다 StackOverflow