Python MySQL插入Python'系列'无法转换为MySQL类型

时间:2018-01-18 14:03:59

标签: python mysql

我有一个数据框,这是我试图插入MySQL数据库的聚合。数据如下所示:

                first                last  count      type  \
group                                                            
1     2018-01-12 00:00:00 2018-01-13 23:00:00    189  Received   
2     2018-01-13 23:15:00 2018-01-14 00:00:00      4    Missed   
3     2018-01-14 00:15:00 2018-01-14 23:45:00     95  Received   
4     2018-01-15 00:00:00 2018-01-15 04:45:00     20    Missed   
5     2018-01-15 05:00:00 2018-01-15 14:00:00     37  Received   
6     2018-01-15 14:15:00 2018-01-15 14:45:00      3    Missed   
7     2018-01-15 15:00:00 2018-01-15 15:45:00      4  Received   
8     2018-01-15 16:00:00 2018-01-16 23:45:00     31    Missed  

        id
group                    
1      ABC123
2      ABC123
3      ABC123
4      ABC123
5      ABC123
6      ABC123
7      ABC123
8      ABC123

当我查看数据类型时,它表明它是一个数据框:

In [990]: type(result)
Out[990]: pandas.core.frame.DataFrame

但是,当我尝试将数据插入MySQL时,出现以下错误:

Failed processing format-parameters; Python 'series' cannot be converted to 
a MySQL type

以下是我用来插入的代码:

for a, b in result.iterrows():

    e_point = result['id'][[a]]
    t = result['type'][[a]]
    num = result['count'][[a]]
    first = result['first'][[a]]
    last = result['last'][[a]]

    try:
       cnx_insert = connector.connect(user='abc', password='abc',
                                         host = 'blah',
                                         port = '3306',
                                         database='some_database')
    except:
        cnx_insert = connector.connect(user='abc', password='abc',
                                     host = 'blah',
                                     port = '3306',
                                     database='some_database')

    cursor_insert = cnx_insert.cursor()
    try:
        values = (id, type, count,  first, last)
        insert_query = ("INSERT INTO some_database.some_table"
                             "(id, message_status, read_intervals, first_reading_time,last_reading_time)"
                             "VALUES(%s, %s, %s, %s, %s)")
        cursor_insert.execute(insert_query, values) 
        cnx_insert.commit()
    except Exception as e:
        print str(id)
        print e
    cnx_insert.close()

我之前从未遇到过麻烦,我尝试过各种各样的事情来处理,例如将数据转换为列表和元组。

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我知道你正在使用连接器保存到mysql。但为什么这么复杂?您可以轻松使用

df.to_sql(table_name, connection, if_exists='append', index=False)

保存您的数据框。