Python mysql错误查询

时间:2017-08-31 04:47:09

标签: python mysql

我在Python上使用mysqlclient运行查询时遇到了麻烦。这是我做的:

  1. 连接到数据库
  2. 查询循环通过dict
  3. 这是我点击索引16时的结果:

      

    _mysql_exceptions.OperationalError :( 2013年,'在查询期间失去与MySQL服务器的连接')

    它在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]))
    

    由于

1 个答案:

答案 0 :(得分:0)

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