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.
Related
So I created a simple table:
c.execute('''CREATE TABLE IF NOT EXISTS friendList (name)''')
I then have a variable 'nombre' which holds the string 'Gabriel'.
I then try the following:
c.execute("INSERT INTO friendList VALUES (nombre);")
And get this:
sqlite3.OperationalError: no such column: nombre
What am I doing wrong?
Try:
c = conn.cursor()
c.execute("INSERT INTO friendList VALUES (?)", (nombre,))
conn.commit() <-- important, needed to save transaction
Since nombre is a variable, you can bind it this way. You could insert it directly by concatenating, but this opens you up to SQL Injection.
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()
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.
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
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