简体   繁体   English

Python sql - 在结果为空的情况下重试执行查询

[英]Python sql - execute query with retry in case the result is empty

Trying to get some data from DB using python sql library (PyODBCConnector).尝试使用 python sql 库(PyODBCConnector)从数据库中获取一些数据。 The Db is mysql. Db 为 mysql。 There is a situation where having an empty result (momentarily), but it will be very rare and on executing sql again the results will be available.有时会出现空结果(暂时),但这种情况非常罕见,再次执行 sql 时,结果将可用。

So trying to find a way to retry in case result-set is empty.所以试图找到一种方法在结果集为空的情况下重试。

Found many examples but these retries are in case of any sql execution error.找到许多示例,但这些重试是在任何 sql 执行错误的情况下。

any suitable example will be of great help.任何合适的例子都会有很大帮助。

Thanks in advance.提前致谢。

You can do something like this:你可以这样做:

i = 0
keepGoing = 0
sql """some sql"""
while keepGoing < 3:
    for i in range(RETRIES):
        try:
            retval = 0
            conn = pyodbc.connect(get_mssql_conn_string(), autocommit=True)  # Don't remove the autocommit
            cursor = conn.cursor()
            cursor.execute(sql)
            fromMSSQL = cursor.rowcount
            conn.close()

        except Exception as e:
            config.LOG.info('Exception executing Stored Proc.')
            config.LOG.info(e)

        else:  # If your sql executes correctly, you only need to check if it returned any resultset
            if fromMSSQL == 0:
                keepGoing += 1
                print('I am going')
            else:
                break

so the while loop outside will keep going n times, unless your count is other than zero, which will cause it to break.所以外面的while循环将继续运行n次,除非你的计数不是零,这会导致它中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM