pandas.to_sql mysql_pandas to_sql

实例:

import pymysql

import pandas as pd

import numpy as np

from sqlalchemy import create_engine

df = pd.DataFrame([[1,"Bob",0],

[2,"Kim",1]],columns=["id","name","sex"])

df

idnamesex

01Bob0

12Kim1

from sqlalchemy import create_engine

engine = create_engine("mysql://{}:{}@{}/{}?charset=utf8".format('username','password','host:port', 'database'))

con = engine.connect()

df.to_sql(name='students', con=con, if_exists='append', index=False)

若表不存在,创建字段都是text,bigint等

df.to_sql参数介绍:

name:string

SQL表的名称。

con:sqlalchemy.engine.Engine或sqlite3.Connection

使用SQLAlchemy可以使用该库支持的任何数据库。为sqlite3.Connection对象提供了旧版支持。

schema:string,optional

指定架构(如果数据库flavor支持此)。如果为None,请使用默认架构。

if_exists:{'fail','replace','append'},默认'fail'

如果表已存在,如何表现。

失败:引发ValueError。

replace:在插入新值之前删除表。

append:将新值插入现有表。

index:布尔值,默认为True

将DataFrame索引写为列。使用index_label作为表中的列名。

index_label:字符串或序列,默认为None

索引列的列标签。如果给出None(默认)且index为True,则使用索引名称。如果DataFrame使用MultiIndex,则应该给出一个序列。

chunksize:int,可选

行将一次批量写入此大小。默认情况下,所有行都将立即写入。

dtype:dict,可选

指定列的数据类型。键应该是列名,值应该是SQLAlchemy类型或sqlite3传统模式的字符串。

你可能感兴趣的:(pandas.to_sql,mysql)