Pandas and SQL; How to select specific row in database?

Question:

I use Pandas to read this SQL using Python (works using SELECT * FROM table):

   ID                      Timestamp   
1  AA34234234234234234234  B534  
2  AA34234234234234234234  B864 
3  cv0Qc0PJFDAP5S4T6pn69Y  B435  
4  cv0Qc0PJFDAP5S4T6pn69Y  B978 

All fields are "TEXT".

Now want to access the last row identical with ID = AA34234234234234234234 and enter this line:

status = pd.read_sql('SELECT * FROM table WHERE ID = AA34234234234234234234', database).tail(1)

I expect to get:

   ID                      Timestamp  
2  AA34234234234234234234  B864

But I get an error instead:

(sqlite3.OperationalError) unrecognized token: "AA34234234234234234234"
[SQL: ‘SELECT * FROM table WHERE ID = AA34234234234234234234’]
(Background on this error at: https://sqlalche.me/e/14/e3q8)

I am sure I do a silly syntax mistake but I can’t seem to narrow down the issue! The link is not helpful for me at least.

Suggestions?

Asked By: Dalalama231123

||

Answers:

Is id string or int? pls check the type

Answered By: MD5

If ID column is of string type, you will need to wrap the ID in quotes:

status = pd.read_sql('SELECT * FROM table WHERE ID = "4234234234234234234234"', database).tail(1)

That is my suspicion of what is happening. I cannot be sure without knowing the table schema.

Answered By: N.Stevenson
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.