Goglides Dev 🌱

Cover image for Create Insert SQL File with 100 Records From Python faker
Roshan Thapa
Roshan Thapa

Posted on

Create Insert SQL File with 100 Records From Python faker

To create an INSERT SQL file with 100 records using the Faker library in Python, you can use the following code:

from faker import Faker

fake = Faker()

# create list to store SQL statements
sqls = []

# generate fake data and create INSERT SQL statements
for i in range(100):
    name = fake.name()
    email = fake.email()
    city = fake.city()
    sql = "INSERT INTO table_name (name, email, city) VALUES ('{}', '{}', '{}')".format(name, email, city)
    sqls.append(sql)

# write SQL statements to file in /tmp directory
with open(r'C:\Users\Administrator\Downloads\fold\insert.sql', 'w') as f:
    for i, sql in enumerate(sqls):
        f.write(sql + '\n')
        print('Inserted record {} of 100'.format(i + 1))
Enter fullscreen mode Exit fullscreen mode

This code generates 100 fake records for a name, email, and city using the Faker class, and then creates an INSERT SQL statement for each record. The SQL statements are stored in a list, and then written to a file named β€œinsert.sql”, with each statement on a separate line.

Note that this is just an example, and you will need to modify the code to match the specific structure of your database table. You may also want to add error handling and additional functionality as needed. For example, you could generate more complex SQL statements with multiple values or different data types.

Top comments (1)

Collapse
 
bkpandey profile image
Balkrishna Pandey

Handy :)