Last active
December 20, 2017 14:53
-
-
Save ripiuk/875937b45c5a25369f4af70f26b557bf to your computer and use it in GitHub Desktop.
Generate data and write it into sql table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pymysql | |
import random | |
SCHEMA = 'schema_name' | |
TABLE_NAME = 'table_name' | |
TABLE_FIELDS = [ | |
'currency', | |
'language', | |
] | |
USER = 'root' | |
PASSWORD = 'root' | |
CURRENCY_CODES = ['USD', 'EUR', 'IDR', 'MYR', 'BGN', 'CZK', 'DKK', 'ILS', 'INR', 'HUF', 'JPY', 'NOK', 'PLN', 'RON', | |
'RUB', 'CNY', 'HKD', 'TWD', 'SEK', 'THB', 'TRY', 'VND'] | |
LANGUAGES = ['de-de', 'id-id', 'ms-my', 'bg-bg', 'cs-cz', 'da-dk', 'he-il', 'hi-in', 'hu-hu', 'ja-jp', 'nb-no', 'pl-pl', | |
'ro-ro', 'ru-ru', 'zh-cn', 'zh-hk', 'zh-tw', 'sv-se', 'th-th', 'tr-tr', 'vi-vn'] | |
MOUNT_OF_DATA = 5 # how much rows do you need | |
connection = pymysql.connect(host='localhost', user=USER, password=PASSWORD, | |
db=SCHEMA, cursorclass=pymysql.cursors.DictCursor) | |
def generate_data() -> list: | |
generated_data = [] | |
for current_amount in range(AMOUNT_OF_DATA): | |
# Here you need to write logic for output fields | |
currency = random.choice(CURRENCY_CODES) | |
language = random.choice(LANGUAGES) | |
# You need to append tuple in the same order as in table | |
generated_data.append((currency, language)) | |
return generated_data | |
try: | |
with connection.cursor() as cursor: | |
sql = "INSERT IGNORE INTO {schema}.{table} ({fields}) " \ | |
"values ({values})".format(schema=SCHEMA, table=TABLE_NAME, fields=', '.join(TABLE_FIELDS), | |
values=", ".join(["%s"] * len(TABLE_FIELDS))) | |
cursor.executemany(sql, generate_data()) | |
connection.commit() | |
finally: | |
connection.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment