Skip to content

Instantly share code, notes, and snippets.

@anton-petrov
Created May 14, 2020 16:03
Show Gist options
  • Save anton-petrov/59eb63296aa7848f2be4b35ce465693a to your computer and use it in GitHub Desktop.
Save anton-petrov/59eb63296aa7848f2be4b35ce465693a to your computer and use it in GitHub Desktop.
Пример сохранения (передачи) Pandas.DataFrame в MySQL
from sqlalchemy import create_engine
import mysql.connector
import pandas as pd
# CustomerID, CustomerName, ContactName, Address, City, PostalCode, Country
customers = {
"CustomerID" : [1, 2, 3, 4, 5],
"CustomerName" : ["Alfreds Futterkiste", "Ana Trujillo Emparedados y helados", "Antonio Moreno Taquería", "Around the Horn", "Ilya Tikhonov"],
"ContactName" : ["Maria Anders", "Ana Trujillo", "Antonio Moreno", "Thomas Hardy", "Anton Petrov"],
"Address" : ["Obere Str. 57", "Avda. de la Constitución 2222", "Mataderos 2312", "120 Hanover Sq.", "Dolgoprudnyi"],
"City" : ["Berlin", "México D.F.", "London", "Luleå", "Moscow"],
"PostalCode" : ["12209", "05023", "05023", "WA1 1DP", "125412"],
"Country" : ["Germany", "Mexico", "Mexico", "UK", "Russia"]
};
table = "Customers"
df = pd.DataFrame(data=customers)
sql = create_engine('mysql+mysqlconnector://root:[email protected]/test', pool_recycle=60)
connection = sql.connect()
try:
df = df.to_sql(table, connection, if_exists='fail');
except ValueError as ve:
print(ve)
except Exception as ex:
print(ex)
else:
print("Table %s created successfully!"%table);
finally:
connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment