Python mysql错误查询

标签 python mysql

我在 Python 上使用 mysqlclient 运行查询时遇到问题。这是我所做的:

  1. 连接到数据库
  2. 通过 dict 循环查询

这是当我达到索引 16 时得到的结果:

_mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query')

它在 Linux 上运行,但不在我的 Windows 环境中运行。

这个错误是什么?

这是我的代码和错误查询的位置

campaignsListReportData = {}

#Connect to Database
db = MySQLdb.connect('mysqlserver', 'user', 'password', 'selecteddb')

cursor = db.cursor()
query = """
           SELECT 
               some column
           FROM 
               some table
           WHERE 
               some condition;
"""
cursor.execute(query)
data = cursor.fetchall()
for row in data:
    campaignReport = {}
    connectionState = False
    while connectionState is False:
        try:
            url = "a URL"
            r = requests.get(url, verify=False)
            feedback = r.json()
            if int(feedback['success']) is 0:
                connectionState = True
            elif int(feedback['success']) is 2:
                connectionState = True
            else:
                cursor.execute("SELECT TRIM(SUM(counter)) FROM d WHERE a = " + str(row[1]))
                counterURL = cursor.fetchone()

                counterURLNumber = 0

                if counterURL[0] == None:
                    counterURLNumber = 0
                else:
                    counterURLNumber = counterURL[0]

                urlData = []
                cursor.execute("""SELECT long_url, counter , TRIM((counter / (SELECT SUM(counter) FROM d WHERE a = """ + str(row[1]) +  """) * 100)) AS 'Percentage' """
                """FROM d """
                """WHERE c = """ + str(row[1]))
                urlQuery = cursor.fetchall()
                for row in urlQuery:
                   urlInfo = {
                        'label': row[0],
                        'value': row[1],
                        'percentage': row[2]
                   }
                   urlData.append(urlInfo)

                campaignsListReportData[str(row[0])] = campaignReport

                connectionState = True
        except requests.exceptions.RequestException as e:
            print(str(datetime.now() - timedelta(minutes=60)))
            print("Connection Failed, Trying again . . .")

db.close()

错误发生于:

cursor.execute("SELECT TRIM(SUM(counter)) FROM d WHERE a = " + str(row[1]))

谢谢

最佳答案

尝试使用 cursor.execute("SELECT TRIM(SUM(counter)) FROM d WHERE a = %s", (str(row[]))) 内置函数 execute 有 2 个参数,第一个是要执行的查询,第二个是 %s 语句,因此我们可以将多个值传递给该选择。请记住,我们可以在一条语句中包含多个 %s,然后在第二个参数中传递值。了解更多 What does %s mean in Python?

关于Python mysql错误查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45973399/

相关文章:

class - 从字典创建类实例属性?

python - 在 headless 模式下使用 ChromeDriver 和 Chrome 以及 --disable-gpu 和 --user-data-dir 参数,GPU 进程已崩溃 x 次错误

python - 如何在 VS Code 上调试? "Bad file descriptor"错误

python - 导入torch(pytorch)时发生错误

java - uri : http://java. sun.com/jsp/jSTL/core 无法在 web.xml 或使用此应用程序部署的 jar 文件中解析

mysql - 如何获得总小时数?

mysql - 如何连接三个表并在 GridView 中获取值

python - django 如何全局使用变量

mysql - SQL 查询 - 在一列上区分其他列的不同值(使用 INNER JOIN)

php - 使用表单中的输入将值选择到变量中