1

csv を解析してデータを SQL Server に挿入するための簡単なスクリプトを作成しました。したがって、非常に奇妙な問題は、 if 条件でそれらを呼び出すと、一部の変数が失われることです。これはスクリプトです:

# DB connection
conn = pypyodbc.connect('DRIVER={SQL Server};SERVER=xxx.xxx.xxx.xxx;DATABASE=SCAN;UID=user;PWD=password')
cursor = conn.cursor()

def main() :
    reader = csv.reader(file(filename, "rb"), delimiter=';')
    for row in reader :
        ip = row[0]
        host = row[1]
        domain = row[2]

        # get Operating System ID
        os_id = getOperatingSystem(row[3])

        manufacturer = row[4]
        model = row[5]

        # get computer_manufacturer ID
        computer_manufacturer = getManufacturer(manufacturer, computer_model)

        arch = getArch(row[6])

        values = [ip, host, domain, os_id, manufacturer, arch]

        hostIP = getHostIP(ip)
        print "hostIP: " +str(hostIP)
        if hostIP == 0:

            print values

            # insert values in DB
            cursor.execute(
                """
                INSERT INTO dbo.hosts (ip, host, domain, os_id, manufacturer, arch_id)
                VALUES (?, ?, ?, ?, ?, ?)
                """, values)
            cursor.commit()


# return host IP ID
def getHostIP(hostIP) :
    cursor.execute("SELECT id FROM mytable WHERE ip = ?", [hostIP])
    row = cursor.fetchone()

    if row is not None :
        return row[0]
    return 0

# return ID of Computer Manufacturer
def getComputerManufacturer(manufacturer, computer_model) :
    cursor.execute("SELECT id FROM manufacturer WHERE manufacturer = ? AND computer_model = ?", [manufacturer, computer_model])
    row = cursor.fetchone()

    if row is not None:
        return row[0]
    else :
        return setComputerManufacturer(manufacturer, computer_model)

私がcursor_executecursor_commit行にコメントした場合、出力はデータを正しく表示します.そうでない場合は、同じcsv行のみが表示されます. ちょっと手伝ってくれませんか?ありがとう

4

0 に答える 0