SQL connector using Python

51 Views Asked by At

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?

1

There are 1 best solutions below

0
AudioBubble On BEST ANSWER

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.