简体   繁体   English

对于没有从服务器获取数据或连接超时,我应该如何在我的数据库 python 代码中进行异常处理

[英]How should I do exception handling in my database python code for no data fetched from server or connection time out

psycopg2.DatabaseError: could not receive data from server: Connection timed out psycopg2.DatabaseError:无法从服务器接收数据:连接超时

Wrap it inside try/except block.将它包裹在 try/except 块中。 like:喜欢:

try:
   conn = conn = dbapi.connect(user=<>,password=<>,host=<>,database=<>)
except psycopg2.DatabaseError:
   <whatever code>

you can use this code in your:您可以在以下位置使用此代码:

 def retrieve_data(db, table_name):
    try:
        comm ="SELECT * FROM {};".format(table_name)
        with db.connect() as conn:
            column_of_sql_table = conn.execute(comm).fetchall()
        return pd.DataFrame(column_of_sql_table)

    except Exception as e:
        print(e)
        return pd.DataFrame()

df = retrieve_data(db, table_name)
if not df.empty :
    < do what ever you want>
else: 
    < rise error>

暂无
暂无

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

相关问题 如何创建到 SQL 服务器的数据库连接并将连接错误消息发送到 Python 中的 email? - How do I create a database connection to SQL Server and send out connection error messages to an email in Python? 如何在python中为mysql连接执行异常处理 - How to do Exception handling for mysql connection in python 通过这种简单的异常处理,我应该在哪里打印输出?(Python) - Where should I print my output at this simple exception handling?(Python) 如何在python中进行异常处理? - How to do exception handling in python? 在 PowerBI 中,如何使用 Python 脚本从数据库中获取最新数据? - In PowerBI how do I fetch the most recent data from my database with my Python script? 如何从远程连接访问python http服务器? - How do I access a python http server from a remote connection? 我的代码未处理异常(python) - My code isn't handling the exception (python) 如何将本地 Python 代码中的变量传递给写入 MySQL 数据库的远程 PHP 脚本? - How do I pass a variable from my local Python code to a remote PHP script that writes to a MySQL database? 如何在Python中重用多个函数的异常处理代码? - How can I reuse exception handling code for multiple functions in Python? 如何在LabVIEW服务器和Python客户端之间建立TCP连接,将来自Python的(数据)角度传输到LabVIEW? - How do I make a TCP connection between LabVIEW server and Python client where (data) angles from Python are to be transferred to LabVIEW?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM