2016-06-30 24 views
0

Ich bin neu bei Python und dachte, ich würde üben, was ich gelernt habe, um eine kleine Aufgabe abzuschließen. Im Wesentlichen füge ich Daten einer kognitiven Kamera in eine Datenbank aus einer .csv-Datei ein, die ich aus dem Internet gezogen habe. Leider musste ich alle Verbindungsdetails weglassen, da es nur von meinem Arbeitscomputer aus zugänglich ist, was bedeutet, dass das Skript nicht ausgeführt werden kann. Zum Problem! Ich habe eine for-Schleife, dass iteriert durch die Kameras im System, läuft dieses Skript:Python for loop drop nach 1 Iteration

#!/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 

Alles ist in Ordnung und die Schleife läuft, wie es soll, aber wenn ich tatsächlich versuchen und die Schleife mit den Daten etwas zu tun einmal und Enden läuft, dann ist dies das vollständige Skript:

#!/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 

ich habe meinen Kopf kratzen worden, wie ich kann nicht sehen, warum es ein Problem gibt, aber vielleicht brauche ich nur ein paar frischen Augen auf sich. Jede Hilfe wäre toll Prost!

+1

Haben Sie versucht, den vollen Satz von Ergebnissen aus der ersten Abfrage abzurufen und sie in eine Liste setzen, anstatt iterieren das Cursorobjekt? Vielleicht ist Ihre Datenbankoperation innerhalb der Schleife mit dem Zustand von 'camCursor' unordentlich. (Im Grunde ändert sich zu 'für Zeilen in der Liste (camCursor):') – Amber

+0

yeah Ich dachte das auch, also arbeite ich jetzt an einer Einfügefunktion, die die Liste nimmt und sieht, ob das irgendwas macht :) Es ist wirklich das Einzige das macht für mich an diesem Punkt Sinn –

+0

Das Problem könnte damit zusammenhängen, dass Sie zwei Cursor auf derselben Verbindung verwenden. Überprüfen Sie diesen Beitrag für weitere Informationen: http://StackOverflow.com/q/5573724/2112269 – Aquiles

Antwort

0

Haben Sie so etwas wie

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

for rows in queryResult: 
    ... 

Ich denke, das könnte das Problem lösen, das ist wahrscheinlich die Tatsache ist, versucht zu tun, dass Sie einen Cursor anstelle der Ergebnisse zu iterieren versuchen.

Sie auf diese Weise auch interessant finden könnte:

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

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

Quelle: https://docs.python.org/2/library/sqlite3.html

+1

das ist es !!! camCursor.execute ("FROM dbo.CAMERAS * SELECT") #Selects die Kameranamen und Verbindungsdetails queryresult = camCursor.fetchall() für die Zeilen in queryresult: .... , die wie ein Zauber danken gearbeitet dich so sehr –