You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL数据库单次数据获取需求及空库场景异常排查

搞定单次获取SQL数据的问题

嗨,我看了你的代码,问题其实很明显——你写了个while True的无限循环!不管数据库里有没有数据,这个循环都会一直跑,所以程序才会反复尝试获取数据。要实现“仅获取一次SQL数据”的需求,咱们把这个死循环去掉就行,再调整下代码结构优化下冗余操作。

先给你梳理下关键问题点:

  • while True会让程序一直重复执行查询逻辑,哪怕数据库空了也停不下来
  • 循环里重复创建cursor、打印服务器信息这些操作完全没必要,纯属冗余
  • 原代码里还有Python2的语法(比如print "test2"),建议改成Python3的写法(print("test2")),避免语法报错

下面是修改后的完整代码:

import mysql.connector
import pafy
import vlc
import time
from mysql.connector.errors import Error

url = "NULL"
try:
    connection = mysql.connector.connect(host='localhost', database='musicbox', user='', password='')
    if connection.is_connected():
        db_Info = connection.get_server_info()
        print("Connected to MySQL Server version ", db_Info)
        cursor = connection.cursor()
        
        # 只执行一次查询,去掉无限循环
        cursor.execute("SELECT * FROM playlist")
        record = cursor.fetchall()
        print(record)
        
        for x in record:
            print(x[0])
            if "youtube" in x[0]:
                # 这里调整空值判断逻辑,直接检查链接字段是否为空
                if not x[0]:
                    print("empty")
                else:
                    print("true")
                    url = x[0]
                    video = pafy.new(url)
                    best = video.getbestaudio()
                    playurl = best.url
                    Instance = vlc.Instance()
                    player = Instance.media_player_new()
                    Media = Instance.media_new(playurl)
                    Media.get_mrl()
                    player.set_media(Media)
                    player.play()
                    time.sleep(1.5)
                    duration = player.get_length() / 1000
                    time.sleep(duration)
                    cursor.execute("DELETE FROM playlist LIMIT 1")
                    connection.commit()

except Error as e:
    print("Error while connecting to MySQL", e)
finally:
    if 'connection' in locals() and connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")

再给你解释下核心改动:

  1. 移除while True无限循环:现在程序只会执行一次SELECT * FROM playlist查询,获取完数据就进入处理逻辑,处理完直接走到finally块关闭连接,程序结束
  2. 清理冗余代码:把重复的获取服务器信息、创建cursor的代码删掉,只保留一次初始化
  3. 调整空值判断逻辑:原代码的if not all(x)可能不符合实际需求(如果表有多个字段,只要有一个为空就会触发),改成直接判断x[0](也就是你的YouTube链接字段)是否为空,更精准
  4. 完善finally块的连接判断:增加'connection' in locals()判断,避免连接失败时调用connection.is_connected()报错

这样修改后,程序就只会获取一次SQL数据,处理完现有内容(或者数据库为空时直接跳过循环)就会正常退出,不会一直重复尝试啦!

内容的提问来源于stack exchange,提问作者PixelWelt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 13:13:19