1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【メモ】mysql.connector-python を用いたときにpython floatがInsertできないといわれた時の方法

Last updated at Posted at 2017-10-12

#mysql.connector-pythonでInsert用いたときのデータ形式
mysql.connector-pythonはどうもnumpy.float形式やtimestamp形式をinsertしてくれないようで

dataはnumpy array 1列目がtimestampの設定です。

numpymysql.py
import numpy as np
import pandas as pd
import datetime as dt
import mysql.connector as ms

class NumpyMySQLConverter(ms.conversion.MySQLConverter):
    """ numpy typeを用いるためのmysql.connector Converter """
    def _float32_to_mysql(self, value):
        return float(value)
    def _float64_to_mysql(self, value):
        return float(value)
    def _int32_to_mysql(self, value):
        return int(value)
    def _int64_to_mysql(self, value):
        return int(value)

def insert_sql(data):
    func_date=np.vectorize(lambda x: dt.datetime(x.year, x.month, x.day, x.hour, x.minute, 0))
    date_data=func_date(data[:,0])
    dbh = ms.connect(
        host=[host_name],
        user=[user_name],
        db=[data_base_name],
        charset='utf8')
    dbh.set_converter_class(NumpyMySQLConverter)
    stmt = dbh.cursor(buffered=True)
    sql = ('INSERT INTO `TABLE`'+
           '(`COLUMN1`, `COLUMN2`) '+
           'VALUES (%s, %s)')
    for i in range(data):
            input_data=(date_data[i], date[i,1])
            #エラーハンドリング
            try:
                stmt.execute(sql, input_data)
            except:
                dbh.commit()
                stmt.close()
                dbh.close()
                return input_data
           #autocommitではないので、明示的にコミットする
           dbh.commit()
    #回線の閉鎖
    stmt.close()
    dbh.close()

とりあえず動いたのでこれで良しと
NumpyMySQLConverterがうまくいくのかいまいち理解はしていません。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?