Python 在 sql table 中插入 pandas 系列数据

Python insert pandas series data in sql table

我正在尝试将数据插入到 sql table 中,其数据类型为 pandas.series.SO,但出现错误 ProgrammingError: ('Invalid parameter type. param-index=1 param-type=Series', 'HY105')

这是代码片段

import pandas as pd
from pandas.io.json import json_normalize
import pyodbc
import json
import numpy as np
cnxn = pyodbc.connect('server connection')
cursor = cnxn.cursor()

cursor.execute("select GEOCODE_ID, JSON from GEOCODE_TBL where JSON is NOT NULL AND GEOCODE_ID = 20")
ID=[]
JSON=""
for row in cursor.fetchall():
 ID.append(row[0]) 
 JSON=row[1]
data = json.loads(JSON)
result = json_normalize(data,'results')
def get_cols(st):
        pol = []
        for i in result['address_components'].apply(json_normalize):
             pol.append(','.join(i.apply(lambda x : x['long_name'] if st in x['types'] else np.nan,1).dropna()))
        return  pol

    result['country'] = get_cols('country') 
    result['room'] = get_cols('room') 
    result['premise'] = get_cols('premise')
sql = "UPDATE OTH_TBL SET GEOCODE_ID=?,country=?,room=?,premise=? where GEOCODE_ID=?"
param= (
   int(ID[0]),
   result['country'],
   result['room'],
   result['premise'],
   int(ID[0])
)
cursor.execute(sql, params)

type(result['country'])pandas.core.series.Series 并且 type(ID[0])int

result['country']
Out[142]: 
0    India
1    India
2    India
3    India
4    India
5    India
6    India
7    India
8    India
9    India
Name: country, dtype: object

有没有人知道如何做到这一点。

谢谢..

多姆尼克

DataFrame.to_sql 命令应该可以解决您的问题

文档在这里:

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html