'Insert user defined datatype into SQLite Database using python function
So I want my database to contain the datatype Item I defined in python:
class Item:
Name = str
L = Location #An Array
Quantity = int
Description = str
I made a table with that as a datatype, the GUI that I use says that column is the Item type:
def CreateTable(DatabaseName ,TableName):
conn = s.connect(DatabaseName)
print ("Opened database successfully")
conn.execute('CREATE TABLE ' + TableName + ' (id integer, Items Item);')
print ("Table created successfully")
conn.close()
Now that I have that I want to insert values, so I defined the following function:
def AddItemToTable(DatabaseName, TableName, Items):
conn = s.connect(DatabaseName)
c = conn.cursor()
c.execute('INSERT INTO '+TableName + '(id, Items) \
VALUES(1,'+Items+')')
conn.commit
conn.close()
I execute these functions:
I = Item
CreateTable('HelloWorld.db', 'again1')
AddItemToTable('HelloWorld.db', 'again1', 'I')
The Database is made, the Table is made, it has the two columns, each column has the right type, but it says theres no column I. If I leave I out of quotes, it tells me it requires an str not type.
Solution 1:[1]
Assuming Item is actually a text type, you need to enclose values with quotes. And for that reason, use double quotes for the SQL string and single quotes for string literals.
c.execute("INSERT INTO "+TableName+" (id, Items) VALUES (1,'"+Items+"')")
But actually the better way is to pass the value as a parameter which you do so as the second argument in cursor.execute() with no worrying about quote enclosure:
c.execute("INSERT INTO "+TableName+" (id, Items) VALUES (1, ?)", Items)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Parfait |
