SQL command shows syntax error during execution - python

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)

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()

INSERT table names using SELECT statement in MySQL

In MySQL, I know I can list the tables in a database with:
SHOW TABLES
But I want to insert a table name into a specified table, for example:
INSERT INTO dataset_names (dataset)
SELECT table_name FROM information_schema.tables
WHERE table_schema = '%s';
But when I execute the above statement, the dataset_names table does not get updated.
I created the master table using:
CREATE TABLE dataset_names (id INT AUTO_INCREMENT PRIMARY KEY, dataset text);
Here is the python code.
dataset_name_query = """
INSERT INTO dataset_names (dataset) values(
SELECT table_name FROM information_schema.tables
WHERE table_schema = '%s');
"""% (tablename)
csv_obj.read()
csv_obj.create()
cursor = createConnection()
#Cursor executing the dataset insert into master table query
cursor.execute(dataset_name_query)
closeCursor(cursor)
You should use a prepared statement, not string formatting. You also need to call connection.commit() to make the changes permanent; replace connection with the name of your connection variable (it's not shown in your example code).
dataset_name_query = """
INSERT INTO dataset_names (dataset)
SELECT table_name FROM information_schema.tables
WHERE table_schema = %s;
"""
cursor = createConnection()
#Cursor executing the dataset insert into master table query
cursor.execute(dataset_name_query, [tablename])
connection.commit()
closeCursor(cursor)
INSERT INTO table_names(name) (SELECT table_name FROM information_schema.tables WHERE table_schema='database_name')
Here the order on insert values and select values must match;
You are use wrong syntax to insert data in a table, you forgot to use 'values' keyword before providing values.
Your command should be something like this -
INSERT INTO dataset_names (dataset) values(
SELECT table_name FROM information_schema.tables
WHERE table_schema = '%s');
This should work.

Can't insert into table if table already exists

So I'm trying to insert a class variable into a mysql database and I'm having problems.
mysql.connector.errors.ProgrammingError: 1050 (42S01): Table 'ordertable' already exists
This message pops up when i try to insert values into a table even when i know the table exists.
order.py
import tkinter
from tkinter import *
import connection
import mysql.connector
class MenuWindow():
def init(self):
db = mysql.connector.connect(host="localhost",user="root", passwd="", database = "pizza")
mycursor =db.cursor()
orderData = [(None, self.varTotal.get())]
for element in orderData:
mycursor.execute("INSERT INTO ordertable (orderid,total) VALUES (?,?)", element)
db.commit()
The table is created in this file
connection.py
def get_connection():
db = mysql.connector.connect(host="localhost",user="root", passwd="", database = "pizza")
mycursor = db.cursor()
mycursor.execute("CREATE TABLE orderTable (orderid INT AUTO_INCREMENT PRIMARY KEY, total INT)")
The error message does not complain about the insert. It complains about the create, because connection.py attempts to create the table when it already exists.
You only need to create the table exactly once, you do not need to create it whenever you reconnect.
Remove the line of
mycursor.execute("CREATE TABLE orderTable (orderid INT AUTO_INCREMENT PRIMARY KEY, total INT)")

PostgreSQL: Unable to drop a specific table named "user"

I'm unable to delete a specific table in my PostgreSQL database. That table is called "user". When I try to run the snippet of code below,
import psycopg2
conn = psycopg2.connect("dbname='mydatabase' user='postgres' host='localhost' password='mypassword'")
cur = conn.cursor()
cur.execute("DROP TABLE user;")
conn.commit()
conn.close()
It spits out the following error
Traceback (most recent call last):
File "dev_psycog.py", line 20, in <module>
cur.execute("DROP TABLE user;")
psycopg2.ProgrammingError: syntax error at or near "user"
LINE 1: DROP TABLE user;
I can delete any other table in my database just fine, but I can't seem to delete my table called "user". Is it because "user" is a reserved keyword?
Quote "user" as below
import psycopg2
conn = psycopg2.connect("dbname='mydatabase' user='postgres' host='localhost' password='mypassword'")
cur = conn.cursor()
cur.execute('DROP TABLE "user";')
conn.commit()
conn.close()
See here.
There is a second kind of identifier: the delimited identifier or
quoted identifier. It is formed by enclosing an arbitrary sequence of
characters in double-quotes (").

Python SQLite3: Cannot Create Table with Variable in Query

I have the following code to create a table if it does not already exist in a database.
TABLE_NAME = 'Test'
sql = sqlite3.connect('DATABASE.db')
cur = sql.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS ? (id TEXT)', [TABLE_NAME])
sql.commit()
But I keep getting sqlite3.OperationalError: near "?": syntax error
I have other code such as cur.execute('INSERT * INTO database VALUES(?,?)', [var1, var2]) that works fine.
That is correct, parameters cannot be used to substitute for database identifiers, only for values. You will have to build the SQL command, with the table name specified, as a string.
The following code creates the table
import sqlite3
sql = sqlite3.connect('DATABASE.db')
cur = sql.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS Test (id TEXT)')
sql.commit()

Categories

Resources