【问题标题】:Pushing results of Imaplib to Mysql database leading to "TypeError"将 Imaplib 的结果推送到 Mysql 数据库导致“TypeError”
【发布时间】:2014-11-02 18:16:55
【问题描述】:

我正在尝试使用 Python 创建我的电子邮件的本地数据库。 我正在使用 Imaplib 从 Imap 服务器读取电子邮件。我的目标是以“SUBJECT”、“SENDER”、“RECEIVER”格式将提取的电子邮件推送到本地 MySql 数据库。

我已经建立了创建本地数据库的代码,阅读电子邮件(带有特定消息)。 我不确定如何编写将结果推送到我的数据库“EMAIL”的代码。

编辑:我已经设法解决了我之前解析邮件并将其添加到数据库的问题。现在我遇到了 Mysql 的类型转换错误。 这是我的新脚本:

 def parse_email(raw_email):
email_complete = email.message_from_string(raw_email)
email_to = email_complete["To"]
email_from = email_complete["From"]
email_header = email_complete.items()
email_msg = get_first_text_block(email_complete)
con = MySQLdb.connect(host="127.0.0.1", # your host, usually localhost
                    user="admin", # your username
                    passwd="pwd", # your password
                    db="sec_crawl") # name of the data base
con.cursor().execute("INSERT INTO email VALUES (?,?,?,?)",
(buffer(str(email_to)),buffer(str(email_from)),buffer(str(email_header)),buffer(str(email_msg))))
con.commit()

在执行此脚本时,我收到以下错误:

TypeError:字符串格式化期间并非所有参数都转换

这是创建数据库的脚本部分:

cur.execute("DROP TABLE IF EXISTS EMAIL")
cur.execute("CREATE TABLE email(email_to TEXT,email_from TEXT,email_header TEXT, email_msg TEXT)")
con.close()

我不确定这个错误。我确实搜索了一些以前的问题

Python MySQLdb TypeError: not all arguments converted during string formatting

但问题仍然存在。 我在 Windows 8 上使用 Python 2.7。

【问题讨论】:

    标签: python mysql imaplib


    【解决方案1】:

    您必须使用 %s 而不是 ?像这样

    con.cursor().execute("INSERT INTO email VALUES (%s,%s,%s,%s)",
     (buffer(str(email_to)),buffer(str(email_from)),buffer(str(email_header)),buffer(str(email_msg))))
    

    '?'通常与 MySQLdb 不支持的预处理语句一起使用。

    【讨论】:

    • 完美。这行得通。我对 SQLite 中的声明感到困惑。
    猜你喜欢
    • 2016-12-13
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多