如何一次使用2个数组?

时间:2018-01-26 19:32:38

标签: python pyodbc

抱歉,我不确定我是否使用了正确的术语。我有一个循环通过“myConnect”服务器名称数组的程序。它创建与每个服务器名称的连接并运行查询。这很好用。

但是如果我在每台服务器上都有多个数据库名称呢?循环访问数据库名称列表以及服务器名称的最佳方法是什么?这是我的服务器名称的工作代码:

import os
import pypyodbc

def func1(connections, firstname, lastname, uname):

        try:
            connection = pypyodbc.connect('Driver={SQL Server};Server=' + connections + ';Database=Database1;Trusted_Connection=yes;')
        except pypyodbc.Error as ex:
            sqlstate = ex.args[0]
            if sqlstate == '28000':
                print("You do not have access.") 
        cursor = connection.cursor() 
        SQLCommand = ("SELECT Active, UserName, FirstName, LastName "      
            "FROM dbo.My_Table "   # table name
            "(nolock)"
            "WHERE FirstName LIKE ? AND LastName LIKE ? AND UserName LIKE ?")
        Values = [firstname + '%', lastname + '%', '%' + uname + '%']
        cursor.execute(SQLCommand,Values)
        results = cursor.fetchone()
        if results:
            print(connections + " " + str(results[0]) + " " + str(results[1]) + " " + str(results[2]) + " " + str(results[3])) # enters results in entry
            connection.close()
        else:
            print(connections + " - NO")
            connection.close()

def start():

    os.system('cls' if os.name == 'nt' else 'clear')
    print (" ")
    while True:
        print("\nPress Ctrl + c to exit.")
        firstname = input('Type the first name: ')
        lastname = input('Type the last name: ') 
        myConnect = ['server1', 'server2', 'server3']  
        for connections in myConnect:
            func1(connections, firstname, lastname, uname)

start()

我应该在myConnect下创建另一个数据库阵列吗?有没有办法将它们组合在一起?也许是这样的?

import os
import pypyodbc

def func1(connections, names, firstname, lastname, uname):

        try:
            connection = pypyodbc.connect('Driver={SQL Server};Server=' + connections + ';Database=' + names + ';Trusted_Connection=yes;')
        except pypyodbc.Error as ex:
            sqlstate = ex.args[0]
            if sqlstate == '28000':
                print("You do not have access.") 
        cursor = connection.cursor() 
        SQLCommand = ("SELECT Active, UserName, FirstName, LastName "      
            "FROM dbo.My_Table "   # table name
            "(nolock)"
            "WHERE FirstName LIKE ? AND LastName LIKE ? AND UserName LIKE ?")
        Values = [firstname + '%', lastname + '%', '%' + uname + '%']
        cursor.execute(SQLCommand,Values)
        results = cursor.fetchone()
        if results:
            print(connections + " " + str(results[0]) + " " + str(results[1]) + " " + str(results[2]) + " " + str(results[3])) # enters results in entry
            connection.close()
        else:
            print(connections + " - NO")
            connection.close()

def start():

    os.system('cls' if os.name == 'nt' else 'clear')
    print (" ")
    while True:
        print("\nPress Ctrl + c to exit.")
        firstname = input('Type the first name: ')
        lastname = input('Type the last name: ') 
        myConnect = ['server1', 'server1', 'server2', 'server2',  'server3']
        databases = ['Database1', 'Database2', 'Database3', 'Database4', 'Database5']
        for connections in myConnect:
            for names in databases:
                func1(connections, names, firstname, lastname, uname)

start()

2 个答案:

答案 0 :(得分:2)

serverDB = {"server1": ['Database1', 'Database2'], 
            "server2": ['Database3', 'Database4'], 
            "Server3": ['Database5']}

for server in serverDB:
    print("connecting to server: " + server)
    for db in serverDB[server]:
        print ( "querying db: " + db)

输出:

connecting to server: server1
querying db: Database1
querying db: Database2
connecting to server: server2
querying db: Database3
querying db: Database4
connecting to server: Server3
querying db: Database5

答案 1 :(得分:1)

您是否希望同时迭代myConnect和数据库?如果是,则可能是zip。或者您是否希望迭代并使用两者中的product之类的东西?

>>> myConnect = ['server1', 'server1', 'server2', 'server2',  'server3']
>>> databases = ['Database1', 'Database2', 'Database3', 'Database4', 'Database5']
>>> from itertools import product
>>> for server, db in zip(myConnect, databases):
...     print(server, db)
...
server1 Database1
server1 Database2
server2 Database3
server2 Database4
server3 Database5
>>> for server, db in product(myConnect, databases):
...     print(server, db)
...
server1 Database1
server1 Database2
server1 Database3
server1 Database4
server1 Database5
server1 Database1
server1 Database2
server1 Database3
server1 Database4
server1 Database5
server2 Database1
server2 Database2
server2 Database3
server2 Database4
server2 Database5
server2 Database1
server2 Database2
server2 Database3
server2 Database4
server2 Database5
server3 Database1
server3 Database2
server3 Database3
server3 Database4
server3 Database5