pymssql: executemany value error - expected a simple type, a tuple or a list

谁说我不能喝 提交于 2019-12-05 14:01:53

I had the same problem, actually having one script that ran and one that didn't. I eventually figured out that the one that was working was all strings and the other had numbers. Digging in further I was finding that the bad type was the numpy.int64 type that numpy uses for integers. Looks like you are using pandas, which also has those number types. I forced it to a string, ran the code again and everything worked.

I wrote a special cleaning function to clean out the tuple before running it:

def tupleGetter(x):
    for i in range(len(x)):
        if str(type(x[i])) == "<class 'numpy.int64'>":
            x[i] = str(x[i])
    return tuple(x)    

Then I ran my code, almost exactly like what you have above:

myValues = (tupleGetter(df.ix[i]) for i in range(len(df)))
cursor.executemany("""INSERT INTO dbo.MyTable([A],[B],[C],[C],[D],[E],[F])
 VALUES (%s, %s, %s, %s, %s, %s)""",
    myValues
    )

conn.commit()

Ran no problem.

Be sure to dropna() as well because that is also a strange type.

As billmanH pointed out, using a type that is not expected by pymssql can generate this error.

Converting to strings works when you want to store strings in the database but I wanted numbers. By passing all as strings and converting on the SQL side, I had total control on the type of the data.

cursor.execute("INSERT INTO my_table(my_int_column, my_numeric_column) VALUES (CAST(%s AS INTEGER),  CAST(%s AS NUMERIC(19, 9)))",
my_tuple_containing_strings)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!