【发布时间】:2019-10-05 23:39:46
【问题描述】:
上下文:我正在尝试通过 Pyodbc 从 SQL Server 查询数据并使用循环逻辑将结果读入下面查询块中的变量中。
问题:有人可以帮我修改下面的代码块,以便它通过循环逻辑正确填充变量吗?我怀疑是因为我在查询游标上使用 fetchall() 方法,每个结果行都转换为列表中的一个元组——这似乎使它下面的循环逻辑无用。有人可以建议一个替代解决方案吗?
from constantcontact import ConstantContact
from constantcontact import Contact
import requests
import json
import pyodbc
username = 'REDACTED'
password = 'REDACTED'
sample_contact_connection = pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};""Server=PC;""Database=leadgen_sandbox;""Username="+username+";""Password="+password+";""Trusted_Connection=yes;")
sample_contact_cursor = sample_contact_connection.cursor()
sample_contact_query = "SELECT first_name,last_name,title,company_name,email_address FROM leadgen_sandbox.dbo.sample_contacts"
sample_contact_connection.autocommit = True
sample_contact_cursor.execute(sample_contact_query)
print(sample_contact_cursor.fetchall())
constantcontact = ConstantContact('REDACTED','REDACTED')
list_id = '1816761971'
for [first_name, last_name, title, company_name, email_address] in sample_contact_cursor.fetchall():
new_contact = Contact()
new_contact.set_first_name(''+first_name+'')
new_contact.set_last_name(''+last_name+'')
new_contact.set_job_title(''+title+'')
new_contact.set_company_name(''+company_name+'')
new_contact.add_list_id(''+list_id+'')
new_contact.set_email_address(''+email_address+'')
response = constantcontact.post_contacts(new_contact)
response_text = json.dumps(response, indent = 4, sort_keys = True)
print(response_text)
sample_contact_connection.close()
【问题讨论】:
标签: python sql-server pyodbc