Python迭代后循环丢弃

时间:2016-06-30 02:51:54

标签: python

我是python的新手,并且认为我会练习我一直在学习完成一项小任务。基本上我是从我从网络上提取的.csv文件中将一个认知相机数据插入数据库。遗憾的是,我不得不省略所有连接细节,因为它只能从我的工作计算机访问,这意味着脚本无法运行。 要问题! 我有一个for循环,遍历系统中的摄像头,运行这个脚本:

 #!/usr/bin/python
import pymssql
import urllib2
import sys
import getpass
import csv
import os

attempts = 0 #connection attempt counter

#check db connection with tsql -H cabernet.ad.uow.edu.au -p 1433 -U ADUOW\\mbeavis -P mb1987 -D library_gate_counts

server = "*****" #sever address
#myUser = 'ADUOW\\' + raw_input("User: ")#  User and password for server. Will this be needed when the script runs on the server? # Ask David
#passw = getpass.getpass("Password: ")          

while attempts < 3: # attempt to connect 3 times
    try: #try connection
        conn = pymssql.connect(server = server, user = '****', password = '****', database = "***", port='1433',timeout = 15, login_timeout = 15)
        break
    except pymssql.Error as e: #if connection fails print error information
        attempts += 1
        print type(e)
        print e.args

camCursor = conn.cursor() #creates a cursor on the database

camCursor.execute("SELECT * FROM dbo.CAMERAS") #Selects the camera names and connection details 



for rows in camCursor:
    print rows

一切都很好,循环运行应该如此,但是当我实际尝试对循环运行的数据执行任何操作时,这就是完整的脚本:

    #!/usr/bin/python
import pymssql
import urllib2
import sys
import getpass
import csv
import os

attempts = 0 #connection attempt counter

#check db connection with tsql -H cabernet.ad.uow.edu.au -p 1433 -U ADUOW\\mbeavis -P mb1987 -D library_gate_counts

server = "*****" #sever address
#myUser = 'ADUOW\\' + raw_input("User: ")#  User and password for server. Will this be needed when the script runs on the server? # Ask David
#passw = getpass.getpass("Password: ")          

while attempts < 3: # attempt to connect 3 times
    try: #try connection
        conn = pymssql.connect(server = server, user = '****', password = '****', database = "***", port='1433',timeout = 15, login_timeout = 15)
        break
    except pymssql.Error as e: #if connection fails print error information
        attempts += 1
        print type(e)
        print e.args

camCursor = conn.cursor() #creates a cursor on the database

camCursor.execute("SELECT * FROM dbo.CAMERAS") #Selects the camera names and connection details 



for rows in camCursor:
    print rows
    cameraName = str(rows[0]) #converts UNICODE camera name to string
    connectionDetails = str(rows[1]) #converts UNICODE connection details to string

    try: #try connection
        #connect to webpage, this will be changed to loop through the entire range of cameras, which will
        #have their names and connection details stored in a seperate database table
        prefix = "***"
        suffix = "**suffix"
        response = urllib2.urlopen(prefix + connectionDetails + suffix, timeout = 5)
        content = response.read() #read the data for the csv page into content
        f = open( "/tmp/test.csv", 'w' ) #open a file for writing (test phase only)
        f.write( content ) #write the data stored in content to file
        f.close() #close file
        print content #prints out content
        with open( "/tmp/test.csv", 'rb' ) as csvFile: #opens the .csv file previously created
            reader = csv.DictReader(csvFile) #reader object of DictReader, allows for the first row to be the dictionary keys for the following rows
            for row in reader: #loop through each row
                start = row['Interval start']
                end = row['Interval stop']
                camName = row['Counter name']
                pplIn = int(row['Pedestrians coming in'])
                pplOut = int(row['Pedestrians going out'])
                insertCursor = conn.cursor()
                insert = "INSERT INTO dbo.COUNTS VALUES (%s, %s, %d, %d)"
                insertCursor.execute(insert, (camName, start, pplIn, pplOut))
                conn.commit()
    except urllib2.URLError as e: #catch URL errors
        print type(e)
        print e.args
    except urllib2.HTTPError as e: #catch HTTP erros
        print type(e)
        print e.code

我一直在挠头,因为我看不出为什么会有问题,但也许我只需要一些新鲜的眼睛。任何帮助都会是很棒的欢呼!

1 个答案:

答案 0 :(得分:0)

你有没有试过像

这样的事情
queryResult = camCursor.execute("SELECT * FROM dbo.CAMERAS")

for rows in queryResult:
    ...

我想这可能会解决问题,这可能是因为您试图迭代光标而不是结果。

你可能会发现这种方式很有趣:

camCursor.execute("SELECT * FROM dbo.CAMERAS")

for rows in camCursor.fetchall():
    ...

来源:https://docs.python.org/2/library/sqlite3.html