python mysql insert python'series'无法转换为mysql类型

oalqel3c  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(395)

我有一个Dataframe,它是一个聚合,我试图在其中插入到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

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

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()

我以前从未遇到过插入问题,我尝试过做各种各样的事情来处理,比如将数据转换成列表和元组。
感谢您的帮助。

pxq42qpu

pxq42qpu1#

我知道你正在使用连接器保存到mysql。但为什么这么复杂?你可以很容易地使用

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

保存Dataframe。

相关问题