我正在设置一个程序,以提取我的Outlook中电子邮件的日期,发件人,主题和正文。但是,当我运行代码时,出现以下错误:
Traceback (most recent call last):
File "C:\Users\zaballgl\Documents\Adhoc\2019\April\ETL_MetricsEmailOutlook.py", line 83, in <module>
cursor.execute("INSERT INTO dbo.BSO_metricsEmailReports([Start_Date],[Name],[Subject],[Body])values(?,?,?,?)",row['Start_Date'],row['Name'],row['Subject'],row['Body'])
pyodbc.ProgrammingError: ('Invalid parameter type. param-index=1 param-type=CDispatch', 'HY105')
这是我从我的前景中提取数据的代码:
import win32com.client
import pandas as pd
import datetime
import numpy as np
import pyodbc
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.Folders('email@outlook.com').Folders('Inbox')
messages = inbox.Items
message = messages.GetFirst()
rec_time = message.CreationTime
body_content = message.body
subj_line = message.subject
sender = message.Sender
year=[]
month=[]
day=[]
hour=[]
minute=[]
subject=[]
sender=[]
body = []
while message:
###This iterates every format of the message.CreationTime and append them to the list above
year.append(message.CreationTime.year)
month.append(message.CreationTime.month)
day.append(message.CreationTime.day)
hour.append(message.CreationTime.hour)
minute.append(message.CreationTime.minute)
## Iterates every subject and append them to the subject variable list
subject.append(message.subject)
## Iterates every sender name and append them to the sender variable list
sender.append(message.Sender)
## Iterates every sender name and append them to the sender variable list
body.append(message.body)
## Goes to the next email
message = messages.GetNext()
## This saves all the information to a context manager
#------COLUMNS FOR THE TABLE---------------#
#StartDate
date = pd.DataFrame({'year':year,'month':month,'day':day,'hour':hour,'minute':minute}) # Had to do this to bypass this error: ValueError: Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True
startDate = pd.to_datetime(date) # Using the above variable this converts this to dtype: datetime64[ns]
#Subject
subject = pd.Series(subject) # just a series of subject data
#Sender
sender = pd.Series(sender) # just a series of sender data
#Body
body = pd.Series(body) # just a series of sender data
df2 = pd.DataFrame({'Start_Date':startDate,'Name':sender, 'Subject': subject, 'Body':body})
这是我的代码,将它们传输到我的MS SQL:
connStr = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server}; Server=someservername;DATABASE=somedatabase;UID=someID;PWD=somepassword@')
cursor = connStr.cursor()
deleteTable = "DELETE FROM dbo.BSO_metricsEmailReports"
cursor.execute(deleteTable)
for index,row in df2.iterrows():
cursor.execute("INSERT INTO dbo.BSO_metricsEmailReports([Start_Date], [Name],[Subject], [Body])values(?,?,?,?)",row['Start_Date'],row['Name'],row['Subject'],row['Body'] )
connStr.commit()
cursor.close()
connStr.close()
They would be sent to a table in my MS SQL 2014 with the below design:
**Column Name** | **Data Type**
Start_Date | datetime
Name | nchar(300)
Subject | nchar(300)
Body | nchar(300)
答案 0 :(得分:0)
我要检查执行行...
我使用?为查询中的每个参数进行设置:
sql_rollup =
'''
SELECT ID,FIRSTNAME, LASTNAME, .USERNAME, numSessions
FROM SESSION INNER JOIN
PERSONNEL ON SESSION.ID = PERSONNEL.ID
WHERE (SessionStartDT between ? AND ?) AND (SiteID = ?)
'''
然后我像这样执行上面的代码:
con = pyodbc.connect(
Trusted_connection='Yes',
Driver='{SQL Server}',
Server=myConfig["database"]["hostname"] + ',' + myConfig["database"]["port"],
Database=myConfig["database"]["database"]
)
con.autocommit = True
cur=con.cursor()
parms = (str(dateFirst), str(dateLast), siteID)
cur.execute(sql_rollup,parms)
请注意,params设置为列表,并且(我怀疑这是问题所在),我将dateFirst和dateLast的数据时间值转换为字符串。
pyodbc无法理解Python对象。另一方面,数据库可以自动解释字符串并将其转换为日期/时间值。
有帮助吗?