使用pandas连接数据库和输出数据库的常见问题

版权声明: https://blog.csdn.net/Peter_Luoz/article/details/89213414

使用哪个包连接数据库

在使用pandas读取和写入数据库的时候,最好不要用pymssql直接去连服务器,读取数据可能不会出问题,但是在写入的时候,会出现一系列的问题。推荐使用sqlalchemy

import pandas as pd
import pymssql
import numpy as np
import matplotlib.pyplot as plt
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

DB_CONNECT_STRING = 'mssql+pymssql://sa:[email protected]:1444/integration?charset=utf8'
engine = create_engine(DB_CONNECT_STRING, echo=True)
DB_Session = sessionmaker(bind=engine)
session = DB_Session()

querry='select * from APPQI_RawData_Overview'
data=pd.read_sql(querry,con=engine)

输出到数据库类型转换出错

这是因为存在nul值可能导致无法转换成数据库支持的形式,可以采取的操作办法主要有两种:

  1. 想办法填充空缺值,避免出错
  2. 导出时全部设置dtype属性为字符型,从而避免类型转换
from sqlalchemy.types import NVARCHAR, Float, Integer
# final_set=pd.concat([A1_DOA_special,RR,operation_wrong_data,A1_DOA_duplicate])
A_na.to_sql(name='test_table8',con=engine,chunksize=10,index=False,if_exists='append',dtype={'Date_diff':Integer})

猜你喜欢

转载自blog.csdn.net/Peter_Luoz/article/details/89213414