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

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

我以前在插入时从未遇到过问题,并且我尝试过采取各种措施来解决问题,例如将数据转换为列表和元组。

感谢任何帮助。

最佳答案

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

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

保存您的数据框。

关于Python MySQL插入Python 'series'无法转换为MySQL类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48323142/

相关文章:

javascript - Python Pandas 突出显示 Dataframe 中的行

php - 如何首先获取最近的记录?

mysql - 仅当多行满足特定条件时才显示查询

mysql - 将标记从 XML 文件加载到 Google Map API

Python集合操作remove(index)

python - 代码不打印文件中的最后一个序列

python - 在 raspbian soft-float 上使用来自 Raspberry Pi 的 Python 的 FTDI D2XX 驱动程序

php - 如何在 GPU 上启用 php 运行 python 脚本?

mysql - 从命令行获取 mysql 列

mysql - 替换表名+mysql中的部分字符串