Search code examples
pythonmysqlsequencepymysql

Python sequence id to mysql with text


I m trying to create id numbers with constant strings. But when I execute the program, it is inserting the input number times my input value. I just want to add like:

dgNotListesi_txtGelisimDurumu_0 dgNotListesi_txtGelisimDurumu_1 dgNotListesi_txtGelisimDurumu_2 dgNotListesi_txtGelisimDurumu_3 ... (to input value.)

Here is m code:

import pymysql.cursors
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='sanane13', db='python')


with conn.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `deneme` (`id_1`) VALUES (%s)"  
        x=0
        y = eval(input("please insert number of students:  "))
        while x<y:

            value = "dgNotListesi_txtGelisimDurumu_%s" %y
            x = x+1
            cursor.execute(sql, (value, ))




conn.commit()

Thank you so much.


Solution

  • You need to use the x variable to construct the value. Replace:

    value = "dgNotListesi_txtGelisimDurumu_%s" %y
    

    with:

    value = "dgNotListesi_txtGelisimDurumu_%s" % x
    

    As a side note, it is usually not a good idea to use eval() - it is dangerous, see: