Get list elements after Insert

Asked

Viewed 45 times

2

I have an empty list that will be fed by inputs.

In case, how do I insert the data stored in this list into a database (SQL Server)? I tried this way but it didn’t work.

import pyodbc, datetime

server = '90.90.90.90'
database = 'TESTE'
username = 'teste'
senha = 'teste123'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()

now = datetime.date.today()

lista = []

v1 = lista.insert(0,input('entre com um numero:' ))
v2 = lista.insert(1,input('entre com o segundo numero:' ))
v3 = lista.insert(2,input('entre com o terceiro numero:'))
v4 = lista.insert(3,'{}'.format(now))

comandoSQL = ('INSERT INTO TESTE_INPUT (VARIAVEL_1, VARIAVEL_2, VARIAVEL_3, 
VARIAVEL_4) VALUES (?,?,?,?)', (v1,v2,v3,v4))
print(comandoSQL)
cursor.execute(comandoSQL)
cnxn.commit()

1 answer

2


The method insert returns None, then all its variables v1, v2, v3 and v4 will have the value None (that is, they will have no defined value).

If you want to access the list values individually, you can use the indexes: lista[0] to take the first element, lista[1] for the second, etc. Then would be:

comandoSQL = ('INSERT INTO TESTE_INPUT (VARIAVEL_1, VARIAVEL_2, VARIAVEL_3, 
VARIAVEL_4) VALUES (?,?,?,?)', (lista[0], lista[1], lista[2], lista[3]))

Not directly related, but if you simply want to add a value at the end of the list, another option is to use append:

lista = []

lista.append(input('entre com um numero:' ))
lista.append(input('entre com o segundo numero:' ))
lista.append(input('entre com o terceiro numero:'))
lista.append('{}'.format(now))

This way the elements are already inserted at the end of the list, and you do not need to control the indexes manually. The use of insert would be more appropriate if you wanted to insert an element in a specific position, but in your case it seems that you just want to add at the end of the list. See the documentation for more details.

  • Thank you! I will try and give feedback on.

  • It worked! It was worth too much...

  • Taking advantage of the topic, you know how to convert a datetime field to Insert?

  • @imaestri That’s another question. But I suggest that before you search the site, because there are already many questions about date conversion. If you don’t find anything for your specific problem, then you create another question. It is not that I do not want to answer, it is that we have to keep the site organized: a question by specific problem (anyway, if you do not find anything and ask another question, I will answer if possible) :-)

  • All right! Thank you..

Browser other questions tagged

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