1
highscore= score
cursor.execute("insert into tble values (hscore) hishscore.getvalue"):

que: score will save into variable highscore. That highscore needs to save on to the database in the field hscore. What is the correct code for insertion and getting value.

4 Answers 4

10

You want to bind the parameter using the ? placeholder:

cursor.execute("INSERT INTO tble (hscore) VALUES (?)", highscore)

If you wanted to insert multiple values, here's a longer form:

cursor.execute(
    """
    INSERT INTO table_name
    (column_1, column_2, column_3)
    VALUES (?, ?, ?)
    """,
    (value_1, value_2, value_3)
)

Your order of VALUES was out of place as well. Good luck!

Sign up to request clarification or add additional context in comments.

2 Comments

no, i need to store value from a variable. i can explain...my project is a gamein python. a high score is generate after the game ends. this value in high score needs to insert into database. how is it possible ?
If you've set the variable highscore to be the value, isn't that what you want to insert? In the example, it will insert a row into the table tble with the column hscore having the value of the Python variable highscore.
0
cursor.execute("insert into tablename(column1,column2) values (?,?);",var1,var2)

I needed the semicolon for it to work for me.

Comments

0

Assuming the column name is 'hscore', and the variable with the value to be inserted is 'highscore':

cursor.execute("insert into tablename([hscore]) values(?)", highscore)

Comments

0
you can follow the below code this is going write column values from csv , good example for your use case

import pyodbc
import io

#credential file for server,database,username,password
with io.open('cred.txt','r',encoding='utf-8')as f2:
    cred_data=f2.read()
    f2.close()
cred_data=cred_data.split(',')
server=cred_data[0]
database=cred_data[1]
username=cred_data[2]
pwd=cred_data[3]



con_obj=pyodbc.connect("DRIVER={SQL Server};SERVER="+server+";DATABASE="+database+";UID="+username+";PWD="+pwd)
data_obj=con_obj.cursor()

#data file with 5 columns
with io.open('data.csv','r',encoding='utf-8')as f1:
    data=f1.read()
    f1.close()
data=data.split('\n')[1:]
i=1001
for row in data:
    lines=row.split(',')
    emp=i
    fname=lines[0].split(' ')[0]
    sname=lines[0].split(' ')[1]
    com=lines[1]
    dep=lines[2]
    job=lines[3]
    email=lines[4]
    data_obj.execute("insert into dbo.EMP(EMPID,FNAME,SNAME,COMPANY,DEPARTMENT,JOB,EMAIL) values(?,?,?,?,?,?,?)", emp,fname,sname,com,dep,job,email)
    con_obj.commit()
    i=i+1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.