SQL connector using Python - 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.

Related

Creating a list in Python and inserting into Oracle table, and then able to retrieve the count ,but the values are not found in oracle table

Creating a list in python and inserting into oracle table , but no records found in oracle table.
Created a list in python.
Created a Oracle table using Python code.
Using executeMany inserted the list.
Run the count(*) query in python and obtained the number of rows and printed in python.
Output : Table has been created in Oracle using python code succesfully , but cannot find the records inserted using python
import cx_Oracle
con = cx_Oracle.connect('username/password#127.0.0.1/orcl')
cursor = con.cursor()
create_table = """CREATE TABLE python_modules ( module_name VARCHAR2(1000) NOT NULL, file_path VARCHAR2(1000) NOT NULL )"""
cursor.execute(create_table)
M = []
M.append(('Module1', 'c:/1'))
M.append(('Module2', 'c:/2'))
M.append(('Module3', 'c:3'))
cursor.prepare("INSERT INTO python_modules(module_name, file_path) VALUES (:1, :2)")
cursor.executemany(None,M)
con.commit
cursor.execute("SELECT COUNT(*) FROM python_modules")
print(cursor.fetchone() [0])
Executing below query "select * from python_modules " should have the 3 records in Oracle SQL Developer tool
Change your commit to con.commit().

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

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

Python and PostgreSQL - GeomFromText

I'm a Python learner,
I'm trying to insert geometry records into PostgreSQL.
If I tried the query without the geometry column, it works fine and all data inserted successfully.
cur.execute("INSERT INTO taxi (userid,carNum) SELECT '"+str(msg['UserID'])+"',"+str(msg['CarNumber']))
Once I try to add the geometry records, nothing happens! execution ends without errors but nothing being inserted into DB.
cur.execute("INSERT INTO taxi (position,userid,carNum) SELECT GeomFromText('POINT("+str(float(msg['longitude']))+" "+str(float(msg['latitude']))+")',4326),'"+str(msg['UserID'])+"',"+str(msg['CarNumber']))
Couldn't figure out what I'm missing here
You need to commit the data to the database.
Check the documentation of psycopg2 http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries
Follow those steps
>>> import psycopg2
# Connect to an existing database
>>> conn = psycopg2.connect("dbname=test user=postgres")
# Open a cursor to perform database operations
>>> cur = conn.cursor()
# Execute a command: this creates a new table
>>> cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
# Pass data to fill a query placeholders and let Psycopg perform
# the correct conversion (no more SQL injections!)
>>> cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",
... (100, "abc'def"))
# Query the database and obtain data as Python objects
>>> cur.execute("SELECT * FROM test;")
>>> cur.fetchone()
(1, 100, "abc'def")
# Make the changes to the database persistent
>>> conn.commit()
# Close communication with the database
>>> cur.close()
>>> conn.close()

Python with SQLite3: select does not display any data

I am writing a very simply database using python and sqlite3. And when I created a table and some data I wanted to display this data using (in terminal) command "Select * From Data", but no data appears, although I checked using other methods that the data is inserted to the table.
How I create my table and data:
db = connect('database.db')
db_cursor = db.cursor()
db_cursor.execute("CREATE TABLE IF NOT EXISTS Data(Id INT, Name TEXT, City TEXT)")
db_cursor.execute("INSERT INTO Data VALUES (1, 'ABC', 'XYZ')")
If I do:
db_cursor.execute("Select * From Data")
print self.db_cursor.fetchall()
the data is displayed.
But when I run a command line and try to do:
sqlite3 database.db
sqlite> .mode column
sqlite> .headers on
sqlite> SELECT * FROM Data;
no data appears. I checked using
sqlite> .tables
that table is generated correctly.
Why sqlite3 run from command line does not display data?
You need to commit your transaction before it is permanently part of the database:
db.commit()
You can use the database connection as a context manager to commit automatically if a block of code executed successfully:
with db:
db_cursor = db.cursor()
db_cursor.execute("INSERT INTO Data VALUES (1, 'ABC', 'XYZ')")
Note that DDL statements (creating tables and other data definitions) are automatically committed, which is why you saw the table in the database, but not the new row.

Categories

Resources