pandas to_sql

1.应用

import pandas as pd
from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://user:password@localhost/test')
df = pd.read_sql('test', engine)
df.to_sql('test', engine)

2.用原生SQL创建表,再使用to_sql进行写入

原因:
1)to_sql无法指定索引
2)to_sql默认将整型映射为bigint(20),字符串映射为text,会浪费很多空间
注意:
1)if_exists='append’表示添加数据,因为数据表是我们提前创建的
2)index=‘False’表示不要将pandas中的索引添加到数据库
3)如果pandas中缺少字段,则在写入sql时,没有指明的列会设为null,或默认值,或自动增加
4) 如果类型不同,会自动更改为sql里的类型,如果还不行则考虑使用dtype参数

import pandas as pd
from sqlalchemy import create_engine
# 使用原生的sql创建表
with engine.connect() as connection:
    result = connection.execute("""
	    CREATE TABLE test (
	        `id` INT NOT NULL AUTO_INCREMENT,
	        `name` VARCHAR(20),
	        PRIMARY KEY (`id`)
		)
		"""
    )
# 再写入数据
df.to_sql('test', engine,if_exists='append',index=False)

3.dtype

查看sqlalchemy与sql映射的数据类型:https://docs.sqlalchemy.org/en/13/core/type_basics.html

from sqlalchemy.types import DATE,CHAR,VARCHAR 
DTYPES = {'col_1字段名称' : DATE, 'col_2':CHAR(4),'col_3':VARCHAR(10)}
df.to_sql(....,dtype = DTYPES)

4.API

def to_sql(self, name, con, schema=None, if_exists='fail', index=True,
               index_label=None, chunksize=None, dtype=None):
参数 描述
name 表名
con 驱动引擎,一般使用SQLAlchemy
if_exists {‘fail’,‘replace’,‘append’},默认’fail’。fail:如果存在表报错;replace:如果存在则覆盖;append:如果存在则追加
index boolean,默认为True,将DataFrame的索引写为列,用index_label作为列名
index_label str或list,默认为none,指定index对应的列名,如果不指定, 默认是index
chunksize int,可选,一次写入多少行,默认所有行都立刻写入
dtype 字典,可选指定列的数据类型

参考:
https://blog.csdn.net/stone0823/article/details/89447982

1.首先用原生sql创建表

2.index = False
不添加索引,如果为ture,则会自动添加index列

3.if_exists=‘append’
默认是覆盖,如果已经存在则报错

5.类型对应关系
1)如果类型不一样会不会报错?比如str 写入 int

2)具体对应关系如何

你可能感兴趣的:(Python,python)