New database table & operation Pandas increase the existing table data

1, connect to the database

import pandas as pd
import pymysql
from sqlalchemy import create_engine
engine = create_engine('mysql+mysqlconnector://root:admin@localhost:3306/nodb')

2, the new table

Creating a DataFrame objects

df = pd.DataFrame({'id':[1], 'name':['a'], 'code':['a'], 'color':['a'], 'yn':[1]})
df

 

df.to_sql('test_tag1', engine, index=False)

 After such an operation is to generate a new table, index parameter indicates the index is not written to the database.

3, the new existing table data

 

df.to_sql('mg_tag1', engine, index=False, if_exists='append')

 

 Adds a parameter over the previous operations, it is enough to add the data table structure.

PS: to_sql parameters

parameter:

name:string

Name of the SQL table.

con:sqlalchemy.engine.Engine或sqlite3.Connection

Use SQLAlchemy can use any database supported by this library.

It provides legacy support for sqlite3.Connection object.

schema:string,optional

Specify a schema (if the database supports). If None, please use the default schema.

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

If the situation existing tables below,

  • fail: initiation ValueError.
  • replace: Delete table before inserting new values.
  • append: new values ​​into an existing table.

index: Boolean value that defaults to True

DataFrame index will write a column. Use index_label as the column name in the table.

index_label: string or sequence, defaults None

Column labels indexed columns. If given None (default) and the index is True,

Then use the index name.

If DataFrame use MultiIndex, it should be given a sequence.

chunksize: int, optional

About to write a batch number. By default, all rows will be written immediately.

dtype: dict, optional

Specify the data type of the column. Should be the key column name value should be SQLAlchemy type,

Sqlite3 traditional mode or a character string.

abnormal:

ValueError exception

When the table is already present and if_exists 'fail' (default).

 

Guess you like

Origin www.cnblogs.com/qinghuaL/p/11414086.html