python mysql连接器查询字符串语法

时间:2014-06-12 02:20:33

标签: python mysql mysql-connector-python

我是python mysql连接器的新手,我正在尝试获取查询的结果,该查询将找到带有p_id = 0的user_ids将转到产品表,查找该城市中有多少产品可用

import mysql.connector
con = mysql.connector.connect(user='user', password = 'pass', host = 'blah.com')

cursor1 = con.cursor(buffered = True)

query = ("SELECT l.user_id, count(u.prod_id)"
        "FROM db1.users as l INNER JOIN db2.product as u "
        "ON l.u_city = u.p_city"
        "WHERE l.p_id =0 GROUP BY l.user_id limit 10;" )
cursor1.execute(query)

查询正在执行mysql但是从python mysql连接器我收到以下错误

C:\Python27\python.exe C:/Python27/Lib/site-packages/mysql/connector/update_campus_user_profile_suset.py
Traceback (most recent call last):

File "C:/Python27/Lib/site-packages/mysql/connector/update_campus_user_profile_suset.py", line 12, in <module>
cursor1.execute(camp_zip)

File "C:\Python27\lib\site-packages\mysql\connector\cursor.py", line 491, in execute
self._handle_result(self._connection.cmd_query(stmt))

File "C:\Python27\lib\site-packages\mysql\connector\connection.py", line 683, in cmd_query
statement))

File "C:\Python27\lib\site-packages\mysql\connector\connection.py", line 601, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 'l.campus_id <2 GROUP BY l.user_id' at line 1

Process finished with exit code 1

2 个答案:

答案 0 :(得分:0)

query ='''SELECT l.user_id, count(u.prod_id) FROM db1.users as l INNER JOIN db2.product as u ON l.u_city = u.p_city WHERE l.p_id =0 GROUP BY l.user_id limit 10'''
  • 始终最好使用('''stmt''')将查询初始化为变量并执行
  • 无需使用;

答案 1 :(得分:0)

看起来你在每一行的末尾都缺少一些空格。尝试:

query = ("SELECT l.user_id, count(u.prod_id) "
        "FROM db1.users as l INNER JOIN db2.product as u "
        "ON l.u_city = u.p_city "
        "WHERE l.p_id = 0 GROUP BY l.user_id limit 10;" )

有时使用多行字符串更自然:

query = ("""
        SELECT l.user_id, count(u.prod_id)
        FROM db1.users as l INNER JOIN db2.product as u
        ON l.u_city = u.p_city
        WHERE l.p_id = 0 GROUP BY l.user_id limit 10
        """)