sqlite3.DatabaseError: malformed database schema (?) - python

I executed the python file in the first try & it worked. But when I included the code "IF NOT EXISTS" in the line cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")& cur.execute("INSERT INTO store VALUES ('Wine Glass,8,10.5')") I am getting an error.
here is my code:
import sqlite3
conn=sqlite3.connect("lite.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")
cur.execute("INSERT INTO store VALUES ('Wine Glass,8,10.5')")
conn.commit()
conn.close()
here is the error:
PS D:\mysite\Interacting with Databases> python 1.py
Traceback (most recent call last):
File "D:\mysite\Interacting with Databases\1.py", line 5, in <module>
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")
sqlite3.DatabaseError: malformed database schema (?)

You have an error in the code:
cur.execute("INSERT INTO store VALUES ('Wine Glass,8,10.5')")
You are providing only single value to three-column table. Replace it with:
cur.execute("INSERT INTO store VALUES ('Wine Glass','8','10.5')")
and your code should work fine.

Related

Copying a table from an in-memory database to a on-disk database in sqlite3

I want to copy one specific table from an in-memory sqlite database, using Python (3.9). Looking in the documentation, I should be able to simply attach the in-memory database to the file database, however while attaching throws no error, when I try to copy the table over, it results in the following error:
Traceback (most recent call last):
File "[insert python file URL here]", line 21, in
file_cursor.execute(f'CREATE TABLE "{table_name}" AS SELECT * FROM db."{table_name}";')
sqlite3.OperationalError: no such table: db.table_name
So, even though it is attaching the database just fine (or at least a memory database), it appears not to be able to find the tables within that database. What can I do?
test code:
import sqlite3
#memory database
conn = sqlite3.connect(":memory:")
cursor = conn.cursor()
#file database
file_conn= sqlite3.connect(r"C:\...\testfile.sqlite") #insert your own URL here
file_cursor = file_conn.cursor()
table_name = "table_name"
#Create table in memory db
cursor.execute(f"CREATE TABLE {table_name} (id INTEGER, Value INTEGER, Value2 INTEGER, Category INTEGER);")
conn.commit()
cursor.execute(f"INSERT INTO {table_name} (id, Value, Value2, Category) "
f"VALUES ('1', '20','20', '2'),"
f"('2', '30','30', '2'),"
f"('13', '17','17','1');")
conn.commit()
# copy table to file db
file_cursor.execute(f"ATTACH DATABASE ':memory:' AS db;")
file_conn.commit()
file_cursor.execute(f"CREATE TABLE '{table_name}' AS SELECT * FROM db.'{table_name}';")
file_conn.commit()
file_conn.close()
conn.close()
You don't need a separate connection to the file db.
Use the connection of the in-memory db to attach the file db:
import sqlite3
#connection to memory db
conn = sqlite3.connect(":memory:")
cursor = conn.cursor()
table_name = "table_name"
#Create table in memory db
cursor.execute(f"CREATE TABLE [{table_name}] (id INTEGER, Value INTEGER, Value2 INTEGER, Category INTEGER);")
cursor.execute(f"INSERT INTO [{table_name}] (id, Value, Value2, Category) "
f"VALUES ('1', '20','20', '2'),"
f"('2', '30','30', '2'),"
f"('13', '17','17','1');")
conn.commit()
# copy table to file db
cursor.execute(r"ATTACH DATABASE 'C:\...\testfile.sqlite' AS db;")
cursor.execute(f"CREATE TABLE db.[{table_name}] AS SELECT * FROM [{table_name}];")
conn.commit()
conn.close()

SQL command shows syntax error during execution

import sqlite3
conn=sqlite3.connect("oyo.db")
conn.execute("CREATE TABLE IF NOT EXIST OYO_HOTELS (NAME TEXT,ADDRESS TEXT,PRICE INT,AMENITIES TEXT,RATING TEXT)")
print("TEBLE CREATED SUCCESSFULLY")
conn.execute("INSERT INTO OYO_HOTELS(NAME,ADDRESS,PRICE,AMENITIES,RATING) VALUES ('OYO1','oyo1_street',450,'bath,kitchen','good')")
cur=conn.cursor()
cur.execute("SELECT * FROM OYO_HOTELS")
table_data=cur.fetchall()
for record in table_data:
print(record)
error
conn.execute("CREATE TABLE IF NOT EXIST OYO_HOTELS (NAME TEXT,ADDRESS TEXT,PRICE INT,AMENITIES TEXT,RATING TEXT)")
sqlite3.OperationalError: near "EXIST": syntax error
As the error says there is a syntax error. It is EXISTS not EXIST.
conn.execute("CREATE TABLE IF NOT EXISTS OYO_HOTELS (NAME TEXT,ADDRESS TEXT,PRICE INT,AMENITIES TEXT,RATING TEXT)"
It is the syntax error, you need to write "CREATE TABLE IF NOT EXISTS" in the place of "CREATE TABLE IF NOT EXIST".
Corrected code:
import sqlite3
conn=sqlite3.connect("oyo.db")
conn.execute("CREATE TABLE IF NOT EXISTS OYO_HOTELS (NAME TEXT,ADDRESS TEXT,PRICE INT,AMENITIES TEXT,RATING TEXT)")
print("TEBLE CREATED SUCCESSFULLY")
conn.execute("INSERT INTO OYO_HOTELS(NAME,ADDRESS,PRICE,AMENITIES,RATING) VALUES ('OYO1','oyo1_street',450,'bath,kitchen','good')")
cur=conn.cursor()
cur.execute("SELECT * FROM OYO_HOTELS")
table_data=cur.fetchall()
for record in table_data:
print(record)

sqlite3.OperationalError: no such table: kupuvac

I need to make two tables for SQLite database, when I try to insert data to the first table, it works without any error, but when I try to insert data for the second table it gives me error: sqlite3.OperationalError: no such table: kupuvac
This code for the first table:
db=sqlite3.connect("magacin")
cursor = db.cursor()
cursor.execute('''
CREATE TABLE magacin(id INTEGER PRIMARY KEY, model TEXT,
proizvoditel TEXT, cena FLOAT , kolicina INTEGER)
''')
The code for the second table(the one that gives the error)
db=sqlite3.connect("kupuvac")
cursor = db.cursor()
cursor.execute('''
CREATE TABLE artikli(id INTEGER PRIMARY KEY,
ime_prezime TEXT, ulica TEXT, kontakt TEXT)
''')
Here`s the full traceback:
Traceback (most recent call last):
File "C:\Users\Nenad\Desktop\Magacin1\1.py", line 8, in <module>
cur.execute('''INSERT INTO kupuvac(ime_prezime, ulica, broj) VALUES(?,?,?)''',(ime, ulica,broj))
sqlite3.OperationalError: no such table: kupuvac
Can anyone please tell me what`s wrong and why it gives me an error?
You haven't supplied code that performs insertion but from what I see in the error I can assume that you passed invalid values for the table name and column names.
Database is "kupuvac" and the table name is "artikli" but you want to insert data into "kupuvac" table which does not exist.

how to populate database using python faker

I am trying to populate a table using python faker and I am getting this error . Here is my code
import psycopg2
from faker import Faker
fake = Faker()
conn = psycopg2.connect(database="testdb", user="****", password="****", host="127.0.0.1", port="5432")
print "Opened database successfully"
cur = conn.cursor()
for i in range (10):
Id =fake.random_digit_not_null()
name = fake.name()
age=fake.random_number(digits=None)
adress =fake.address()
salary = fake.random_int(min=0, max=9999)
cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (Id,name,age,adress,salary)");
conn.commit()
print "Records created successfully";
conn.close()
here is the error
Traceback (most recent call last):
File "fakegenerator.py", line 16, in <module>
VALUES (Id,name,age,adress,salary)");
psycopg2.ProgrammingError: column "id" does not exist
LINE 1: ...OMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (Id,name,ag...
^
HINT: There is a column named "id" in table "company", but it cannot be referenced from this part of the query.
You're not filling in the values into your query, instead you're sending the string as-is to the database. This would actually fill your query with values:
cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (%s, %s, %s, %s, %s)", (Id, name, age, adress, salary));
This wraps the variables filled with the values you want to insert into a tuple and let's psycopg2 handle quoting your strings correctly which is less work for you and keeps you safe from SQL injection, should you use your code as a base for productive code. This is documented in the module's documentation.
the sql request in cur.execute seems to be a problem try this
cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES ({},{},{},{},{})".format(Id,name,age,adress,salary));

How do I insert data into table?

I have created table using this create command as:
CREATE TABLE test_table(id INT PRIMARY KEY,name
VARCHAR(50),price INT)
i want to insert into this table wherein values are stored already in variable
bookdb=# name = 'algorithms'
bookdb-# price = 500
bookdb-# INSERT INTO test_table VALUES(1,'name',price);
I get the following error:
ERROR: syntax error at or near "name"
LINE 1: name = 'algorithms'
Can anyone point out the mistake and propose solution for the above?
Thanks in advance
Edit:
import psycopg2
import file_content
try:
conn = psycopg2.connect(database='bookdb',user='v22')
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS book_details")
cur.execute("CREATE TABLE book_details(id INT PRIMARY KEY,name VARCHAR(50),price INT)")
cur.execute("INSERT INTO book_details VALUES(1,'name',price)")
conn.commit()
except:
print "unable to connect to db"
I have used the above code to insert values into table,variables name and price containing the values to be inserted into table are available in file_content python file and i have imported that file.The normal INSERT statement takes values manually but i want my code to take values which are stored in variables.
SQL does not support the concept of variables.
To use variables, you must use a programming language, such as Java, C, Xojo. One such language is PL/pgSQL, which you can think of as a superset of SQL. PL/PgSQL is often bundled as a part of Postgres installers, but not always.
I suggest you read some basic tutorials on SQL.
See this similar question: How do you use script variables in PostgreSQL?
don't have postgres installed here, but you can try this
import psycopg2
import file_content
try:
conn = psycopg2.connect(database='bookdb',user='v22')
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS book_details")
cur.execute("CREATE TABLE book_details(id INT PRIMARY KEY,name VARCHAR(50),price INT)")
cur.execute("INSERT INTO book_details VALUES(1, '%s', %s)" % (name, price))
conn.commit()
except:
print "unable to connect to db"
If you are using PSQL console:
\set name 'algo'
\set price 10
insert into test_table values (1,':name',:price)
\g

Categories

Resources