python MySQLdb 插入表时出现无效语法

1 投票
4 回答
6628 浏览
提问于 2025-04-15 20:56
## COMMENT OUT below just for reference
""
cursor.execute ("""
    CREATE TABLE yellowpages
    (
        business_id     BIGINT(20) NOT NULL AUTO_INCREMENT,
        categories_name VARCHAR(255),
        business_name   VARCHAR(500) NOT NULL,
        business_address1 VARCHAR(500),
        business_city VARCHAR(255),
        business_state VARCHAR(255),
        business_zipcode VARCHAR(255),
        phone_number1 VARCHAR(255),
        website1 VARCHAR(1000),
        website2 VARCHAR(1000),
        created_date datetime,
        modified_date datetime,
        PRIMARY KEY(business_id)
    )
""")
""
## TOP COMMENT OUT (just for reference)

## code
website1g = "http://www.triman.com"
business_nameg = "Triman Sales Inc"
business_address1g = "510 E Airline Way"
business_cityg = "Gardena"
business_stateg = "CA"
business_zipcodeg = "90248"
phone_number1g = "(310) 323-5410"
phone_number2g = ""
website2g = ""

cursor.execute ("""
    INSERT INTO yellowpages(categories_name, business_name, business_address1, business_city, business_state, business_zipcode, phone_number1, website1, website2)
    VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s')
""", (''gas-stations'', business_nameg, business_address1g, business_cityg, business_stateg, business_zipcodeg, phone_number1g, website1g, website2g))


cursor.close()
conn.close()

我一直收到这个错误

  File "testdb.py", line 51
    """, (''gas-stations'', business_nameg, business_address1g, business_cityg, business_stateg, business_zipcodeg, phone_number1g, website1g, website2g))
              ^
SyntaxError: invalid syntax

你知道为什么吗?

提前谢谢你的帮助


更新 #2,我已经去掉了“categories_name”上的两个单引号,但现在即使

import MySQLdb  

conn =  MySQLdb.connect(host="localhost",port=22008,user="cholestoff",passwd="whoami",db="mydatabase")  
cursor = conn.cursor()  

## Find mysql version  
cursor.execute ("SELECT VERSION()")  
row = cursor.fetchone()  
print "server version:", row[0]  

website1g = "http://www.triman.com"  
business_nameg = "Triman Sales Inc"  
business_address1g = "510 E Airline Way"  
business_cityg = "Gardena"  
business_stateg = "CA"  
business_zipcodeg = "90248"  
phone_number1g = "(310) 323-5410"  
phone_number2g = ""  

cursor.execute ("""
    INSERT INTO yellowpages(categories_name, business_name)
    VALUES ('%s','%s')
""", ('gas-stations', business_nameg))              

cursor.close()  
conn.close()  

还是出现了这个错误

server version: 5.1.33-community  
Traceback (most recent call last):  
  File "testdb.py", line 23, in <module>  
    """, ('gas-stations', business_nameg))  
  File "C:\Python26\lib\site-packages\MySQLdb\cursors.py", line 173, in execute  
    self.errorhandler(self, exc, value)  
  File "C:\Python26\lib\site-packages\MySQLdb\connections.py", line 36, in   defaulterrorhandler  
    raise errorclass, errorvalue  
_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 'gas-stations'',''Triman Sales Inc'')' at line 2")

再次感谢你的帮助

4 个回答

0

你不能使用两个单引号(比如 ''gas-stations'')来表示字符串。你可以用一个单引号('gas-stations')或者用双引号("gas-stations")来表示。

1

针对你的第二个问题,你需要去掉你在VALUES部分的所有单引号字符……应该写成 VALUES (%s,%s) 而不是 VALUES ('%s','%s')

一般来说,规则非常简单:对于每一个参数,在你的SQL语句中放一个占位符(在mySQLdb中这个占位符是 %s),然后在你的参数元组中提供一个Python表达式。接下来,放轻松,让接口软件为你处理好一切。这包括正确地给字符串加引号。别试图自己去做。特别是,字符串表达式应该和你期望后面取回的内容完全一致。

举个例子:一个加油站的 business_name 是 "O'Reilly's Pump'n'Go",在Python中表示为字符串常量。最终在构建的SQL中会变成 ...VALUES(...,'O''Reilly''s Pump''n''Go',...,而你根本不需要去考虑这些。

2

我觉得你的问题出在这里:

''gas-stations''

这会导致语法错误。你可能想用一组引号:

'gas-stations'

如果你想把值 'gas-stations' 插入到数据库中,并且想保留引号的话,你可以选择转义引号,或者用双引号把字符串包起来,而不是单引号:

"'gas-stations'"

“上箭头”指向错误位置的原因是你的代码行太长,导致在控制台上换行了。你可以缩短代码行,或者把控制台窗口调宽,这样就能看到错误的真实位置了。

撰写回答