Python SQLite3: Cannot Create Table with Variable in Query - python

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

Related

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.

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)

SQL connector using Python

I have a SQL database which I wish to run a query on through python. I have the following code:
sql='select * from mf where frequency=220258.0;'
cur.execute(sql)
Where I use the same select command in sqlite3 directly it works, but through Python no database entries are outputted.
What am I doing wrong?
Consider this SQLite database.
$ sqlite3 so.sqlite3 .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE t (f1 integer, f2 text);
INSERT INTO "t" VALUES(1,'foo');
INSERT INTO "t" VALUES(2,'bar');
INSERT INTO "t" VALUES(3,'baz');
COMMIT;
Python connects and queries this database like this.
import sqlite3
con = sqlite3.connect("so.sqlite3")
cur = con.cursor()
cur.execute("select * from t where f1 = 2")
print(cur.fetchone())
Output:
(2, 'bar')
You have to use one of cur.fetchone(), cur.fetchall(), or cur.fetchmany() to get rows from the cursor. Just doing cur.execute() does not return the rows.

sqlite3 python ATTACH DATABASE copy table .schema

System
Python 2.7
SQLite3
Code
I want to restore a backup of a database by copying a table from the _bak.db to the being used .db.
conn = sqlite3.connect(os.path.join("data", "db", "Kanji-story.db"))
c = conn.cursor()
c.execute("DROP TABLE IF EXISTS current")
c.execute("ATTACH DATABASE ? AS db2", (os.path.join('data', 'db', 'Kanji-story_bak.db'),))
# TODO Code for Creating table with the same structure
c.execute("INSERT INTO main.current SELECT * FROM db2.current")
Question
To execute the last statement I first have to create a table in Kanji-story.db with the same structure as Kanji-story_bak.db (see # TODO). How do I create a TABLE with the same structure? I know there is .schema command in SQLite3, but how do I effectively use that command to make a new table?
Inspired by the answer of #CL. , the full code is:
conn = sqlite3.connect(os.path.join("data", "db", "Kanji-story.db"))
c = conn.cursor()
c.execute("DROP TABLE IF EXISTS current")
c.execute("ATTACH DATABASE ? AS db2", (os.path.join('data', 'db', 'Kanji-story_bak.db'),))
c.execute("SELECT sql FROM db2.sqlite_master WHERE type='table' AND name='current'")
c.execute(c.fetchone()[0]) # Contains: CREATE TABLE current (framenum INTEGER, nextKanji INTEGER)
c.execute("INSERT INTO main.current SELECT * FROM db2.current")
conn.commit()
conn.close()
SQLite has no mechanism to execute indirect commands.
To get the original table definition, you have run the same query used internally by .schema:
SELECT sql FROM db2.sqlite_master WHERE type='table' AND name='current'
My sqlite3 version 3.18.0 has create table main.current as select * from db2.current

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