【问题标题】:How to connect with Pyodbc with function?如何通过函数连接 Pyodbc?
【发布时间】:2017-08-04 15:00:36
【问题描述】:

在使用函数启动程序时,我遇到了无法连接到数据库的问题。如果我不使用函数启动它,它就可以正常工作。 我的程序从 serverlist.txt 中获取计算机名称并在数据库中查找它。然后它会为我提供该计算机的“位置 ID”。

此版本有效:

import os
import shutil
import fileinput
import pypyodbc

def replaceid(servername):
    try:
        cursor = connection.cursor()

        SQLCommand = ("SELECT Name, Location_ID "
            "FROM dbo.I_Location "   # table name
            "with (nolock)"
            "WHERE Name = ?")
        Values = [servername]
        cursor.execute(SQLCommand,Values)
        results = cursor.fetchone()
        if results:

            print (" Name: " + results[0] + " Location ID: " + str(results[1]))
            print (" ")
        else:
            print (" Location ID for " + servername + " does not exist.")
            print (" ")
            connection.close()
    except:
        print("Database is down or you are not connected to network.")
        exit()

def grab(servername):
# copy config from remote computer

    source = r'//' + servername + '/c$/Administrator/'
    dest = "."
    file = "Admin.config"
    if os.path.isfile(os.path.join(source, file))
        try:
            shutil.copyfile(os.path.join(source, file), os.path.join(dest, file))

        except:
            print (" Local directory you are copying to does not exist.")
    else: 
        pass

    replaceid(servername)



os.system('cls' if os.name == 'nt' else 'clear')
array = []
with open("serverlist.txt", "r") as f:
    for servername in f:

        try:
            connection = pypyodbc.connect('Driver={SQL Server};Server=mydbx;Database=WinOasis;Trusted_Connection=yes;') 
        except pypyodbc.Error as ex:
            sqlstate = ex.args[0]
            if sqlstate == '28000':
                print ("You do not have access.")
        grab(servername.strip())

当我在底部添加 start() 函数时,它不起作用。它移动到说 数据库已关闭或您未连接到网络。

import os
import shutil
import fileinput
import pypyodbc

def replaceid(servername):
    try:
        cursor = connection.cursor()

        SQLCommand = ("SELECT Name, Location_ID "
            "FROM dbo.I_Location "   # table name
            "with (nolock)"
            "WHERE Name = ?")
        Values = [servername]
        cursor.execute(SQLCommand,Values)
        results = cursor.fetchone()
        if results:

            print (" Name: " + results[0] + " Location ID: " + str(results[1]))
            print (" ")
        else:
            print (" Location ID for " + servername + " does not exist.")
            print (" ")
            connection.close()
    except:
        print("Database is down or you are not connected to network.")
        exit()

def grab(servername):
# copy config from remote computer

    source = r'//' + servername + '/c$/Administrator/'
    dest = "."
    file = "Admin.config"
    if os.path.isfile(os.path.join(source, file))
        try:
            shutil.copyfile(os.path.join(source, file), os.path.join(dest, file))

        except:
            print (" Local directory you are copying to does not exist.")
    else: 
        pass

    replaceid(servername)

def start():
    # Option 1
    os.system('cls' if os.name == 'nt' else 'clear')
    array = []
    with open("serverlist.txt", "r") as f:
        for servername in f:

            try:
                connection = pypyodbc.connect('Driver={SQL Server};Server=mydbx;Database=WinOasis;Trusted_Connection=yes;') 
            except pypyodbc.Error as ex:
                sqlstate = ex.args[0]
                if sqlstate == '28000':
                    print ("You do not have access.")
            grab(servername.strip())

start()

关于造成这种情况的任何想法?

【问题讨论】:

    标签: python sql-server pyodbc


    【解决方案1】:

    当你把连接放在启动函数中时,它变成了一个本地对象,其他函数无法获得连接!!!

    如果每个函数使用相同的连接,则必须将连接作为对象传递给它们!!!

    grab(servername.strip(),connection)
    def grab(servername ,connection):
    def replaceid(servername,connection):
    

    这样改应该没问题(在try部分放grab函数)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-07
      相关资源
      最近更新 更多