Insert data tuple into the same database cell

0

I have the following script:

import pymysql

cobertura = (10, 20)
base_de_dados = pymysql.connect("localhost", "root", "senha", "base_de_dados")
cursor = base_de_dados.cursor()
cursor.executemany("INSERT INTO individuo VALUES (NULL, %s)", (cobertura))
base_de_dados.commit()
base_de_dados.close()

When I run, instead of values (10, 20) being saved as tuples in my database, they are written to different rows. For example, the value 10 in column 1 row 1 and the value 20 in column 1 row 2.

How do I get values to be saved as tuples in the same cell?

Thanks to those who can help me!

    
asked by anonymous 11.10.2017 / 19:57

1 answer

1

The initial error is in the form that is passing the value to the function. When you do (cobertura) you are not creating a tuple, because so Python interprets only that the parentheses are to control the precedence of operators in the expression. Proof of this, you just need to check the length of the tuple:

print len( (cobertura) ) # 2

The result will be 2, corresponding to the values 10 and 20 in coverage. That is, doing (cobertura) is the same as just cobertura . To create a tuple with the value of the variable, you need to insert a comma after its name:

(cobertura,)

With the comma, Python goes on to understand that you want to create a new tuple with the value of cobertura . But another point is that the tuple will not be converted to string automatically. You will need to manually convert it:

(str(cobertura),)

So, assuming the database is properly configured, it will work as desired.

    
11.10.2017 / 20:37