Insert Data Tuple into same database cell

Asked

Viewed 253 times

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 the values (10, 20) being saved as tuples in my database, they are written on different lines. For example, value 10 in column 1 row 1 and value 20 in column 1 row 2.

How do I save values as tuples in the same cell?

Thank you who can help me!

  • You want to save in the bank to string (10, 20)?

  • Exactly that @Andersoncarloswoss

  • 2

    Try placing a comma after the cobertura: (cobertura,). Without it, Python does not define a tuple, but rather uses parentheses to control the preceedences of the expression. With the comma he will understand that what he wants to do is create a tuple.

  • I edited the code this way: cursor.executemany("INSERT INTO individual VALUES (NULL, %s)", (coverage,) Presented error: Typeerror: not all Arguments converted During string formatting

  • 1

    Then you’ll need to convert the tuple to string: (str(cobertura),)

  • Complicated like that. The message says that the content has been truncated, so you probably set the table wrong. Type and length of column cobertura?

  • @Andersoncarloswoss, first excuse, the solution you passed : Then you need to convert the tuple to string: (str(coverage),). It worked correctly, I had forgotten to modify the data type in my table to VARCHAR. Thank you very much! Do not want to post as response?

Show 2 more comments

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, as Python interprets only that parentheses are to control the precedence of operators in the expression. Proof of this, just 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, do (cobertura) is the same as just cobertura. To create a tuple with the variable value, you need to insert a comma after its name:

(cobertura,)

With the comma, Python now understands 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. It will be necessary to convert it manually:

(str(cobertura),)

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.