【问题标题】:How to write to a file if DB connection fails如果数据库连接失败,如何写入文件
【发布时间】:2018-10-09 05:13:19
【问题描述】:

我有下面的 Python 脚本,它工作得很好,但我想介绍一些故障安全选项 .. 故障安全选项是 ..

1) 如果我找不到(在本例中)Michael 我想写入文件 ERROR ..

2) 如果数据库由于某种原因不允许我连接,我想写入另一个文件 CONNECTION_ERROR

这是我的脚本:

#! /usr/bin/python

import pymssql

import sys
sys.path.insert(0, '/opt/mount/safe')
from secrets import password

conn = pymssql.connect(
server="server",
port=port,
user="user",
password=password,
database="database")
conn

cursor = conn.cursor()
cursor.execute("SELECT name, address FROM database WHERE name = 'michael'")
with open('safe/file.txt', 'w') as f:
     for row in cursor.fetchall():
        print ( "Person " + (row[0])),
        print ( "has this address " + (row[1]))
        f.write(str( "Person " + (row[0])))
        f.write("%s\n" % str( " has this address " + (row[1])))
conn.close()

【问题讨论】:

  • 很难得到这个问题的答案,除非您 (a) 先自己尝试,然后让人们看看有什么问题,或者 (b) 提出具体问题。现在,我会在这段代码中添加一些Try/Catch blocks——这样你就可以捕获错误并根据需要将它们写入文件
  • 听起来你想实现logging。该页面包含几个教程的链接。

标签: python logging error-handling pymssql info


【解决方案1】:

花了我一段时间,但下面的效果真的很好

import sys, pymssql, string, os, calendar, datetime, traceback, socket, platform

try:
        d = datetime.datetime.now()
        log = open("LogFile.txt","a")
        log.write("----------------------------" + "\n")
        log.write("----------------------------" + "\n")
        log.write("Log: " + str(d) + "\n")
        log.write("\n")
# Start process...
        starttime = datetime.datetime.now()
        log.write("Begin process:\n")
        log.write("     Process started at "
        + str(starttime) + "\n")
        log.write("\n")

xxxxxx 

CODE HERE

XXXXXX



        endtime = datetime.datetime.now()
# Process Completed...
        log.write("     Completed successfully in "
        + str(endtime - starttime) + "\n")
        log.write("\n")
        log.close()
except:
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
# Concatenate information together concerning
# the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info())
# Return python error messages for use in
# script tool or Python Window
        log.write("" + pymsg + "\n")
        log.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-02
    相关资源
    最近更新 更多