Search code examples
pythonmysqlrandompymysql

pymysql inserting random numbers into a column using python


I want to insert random numbers to a MySQL column rnd_value with 100 random numbers including and between 1 to 100 using python.

I will generate random numbers from python using

random.randrange(1,100)

I have added MYSQL query to the database

 CREATE SCHEMA `random_values` ;
CREATE TABLE `exercise`.`random_values` (
  `id` INT NOT NULL AUTO_INCREMENT COMMENT '',
  `rnd_value` INT NULL COMMENT '',
  PRIMARY KEY (`id`)  COMMENT '');

I use pymysql connector to insert data into MySQL database. Can anyone suggest me to how to insert these random numbers into a MySQL column using python?


Solution

  • Thanks for all the responses, this code seems to work for me,

    import pymysql
    import random
    
    connection=pymysql.connect(host='localhost',user='root',password='server',
                               db='exercise',charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)
    
    
    try:
        with connection.cursor() as cursor:
            for i in range (1, 101):
                j=random.randrange(1,100)
                sql = "INSERT INTO exercise.random_values(rnd_value) VALUES (%s)"
                cursor.execute(sql,(j))
                connection.commit()
    
    finally:
        connection.close()