hmalkan
hmalkan

Reputation: 11

In Python, how to define a function which inserts the arguments of the function to a table in database?

i want to define a function (named "kayitEkle") which inserts the arguments of function to a table (named "biTablo") in database:

import sqlite3

connect = sqlite3.connect("obs.db")
cursor = connect.cursor()

def tabloOlustur():
    cursor.execute("CREATE TABLE IF NOT EXISTS biTablo(ad TEXT, soyad TEXT, numara TEXT, puan REAL)")
    connect.commit()


tabloOlustur()

def kayitEkle(ad, soyad, numara, puan):
    cursor.execute("INSERT INTO biTablo(ad, soyad, numara, puan) VALUES(? ? ? ?)",(ad,soyad,numara,puan))
    connect.commit()

kayitEkle('ahmet', 'yılmaz', '08067', 50)

but i get this message:

Traceback (most recent call last):
 File "C:/Users/pc/PycharmProjects/ikinciBahar/ogrenmeDatabase.py", line 234, in <module>
   kayitEkle('ahmet', 'yılmaz', '08067', 50)
 File "C:/Users/pc/PycharmProjects/ikinciBahar/ogrenmeDatabase.py", line 231, in kayitEkle
   cursor.execute("INSERT INTO biTablo(ad, soyad, numara, puan) VALUES(? ? ? ?)",(ad,soyad,numara,puan))
sqlite3.OperationalError: near "?": syntax error

what is wrong? what should i do?

Upvotes: 0

Views: 90

Answers (4)

Nurjan
Nurjan

Reputation: 6073

If I am not wrong this should work:

cursor.execute("INSERT INTO biTablo(ad, soyad, numara, puan) VALUES(%s, %s, %s, %s)", (ad,soyad,numara,puan))

Upvotes: 0

zelenov aleksey
zelenov aleksey

Reputation: 398

You should probably use python .format and change your line from

   cursor.execute("INSERT INTO biTablo(ad, soyad, numara, puan) VALUES(? ? ? ?)",(ad,soyad,numara,puan))

to

   cursor.execute("INSERT INTO biTablo(ad, soyad, numara, puan) VALUES({},{},{},{})".format(ad,soyad,numara,puan))

Upvotes: 1

grcanosa
grcanosa

Reputation: 36

You need to compose the string correctly. Asumming ad,soyad,numara are strings and puan is a number:

cursor.execute(INSERT INTO biTablo VALUES(\"%s\", \"%s\", \"%s\", %f);" % (ad,soyad,numara,puan))

Upvotes: 1

ikuamike
ikuamike

Reputation: 335

In your cursor.execute use VALUES(%s, %s, %s, %s)

Upvotes: 1

Related Questions