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.

Century
  • 285
  • 6
  • 20
Lijo David
  • 13
  • 1
  • 1
  • 4

4 Answers4

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!

FlipperPA
  • 13,607
  • 4
  • 39
  • 71
  • 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 ? – Lijo David Apr 09 '18 at 13:36
  • 1
    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`. – FlipperPA Apr 09 '18 at 14:42
0
cursor.execute("insert into tablename(column1,column2) values (?,?);",var1,var2)

I needed the semicolon for it to work for me.

dbc
  • 104,963
  • 20
  • 228
  • 340
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)
walter's human
  • 103
  • 1
  • 1
  • 9
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