I'm new to Python and working with SQL queries. I have a database that contains a table with meetings and their date along with an ID. What I want to do is check what meetings are happening on today's date. The code below results in showing all the meeting ID's that are happening on todays date. However I then want to check if a certain meeting ID is in the results, which I have stored as a variable, and if it is in there to carry out an IF function so I can then elaborate.
cur.execute("SELECT id FROM meeting WHERE DATE(starttime) = DATE(NOW())")
for row in cur.fetchall() :
print row[0]
You can ask the database to tell you if the id is there:
cur.execute("SELECT id FROM meeting WHERE DATE(starttime) = DATE(NOW()) AND id=%s", (id,))
if cur.rowcount:
# The id is there
else:
# The id is not there.
I am assuming that you are using MySQLdb here; different database adapters use slightly different query parameter styles. Others might use ? instead of %s.
Related
I am trying to run two select queries one from a puzzle table and one from a table that stores the ids of the puzzles a user has played. I want the ids from the puzzles selected and then the ids for the puzzles played selected so that i can compare the two lists to find the puzzles the users has not yet played.
I am having an issue because the first query runs correctly but the second isn't as it seems to be taking the two values from the first query. How do i stop this? Its like i need to close the connection before running the next select query.
cur=connection.cursor()
cur.execute("SELECT id FROM puzzles WHERE approved =? AND level=? ",(1, UserLevel))
puzzle_rows=cur.fetchall()
print(puzzle_rows)
cur=connection.cursor()
cur.execute("SELECT id FROM puzzle_users WHERE name =?",(username))
played_rows=cur.fetchall()
print(played_rows)
not_played = [[x for x in puzzle_rows if x not in played_rows]]
print(not_played)
The error i get is:
conn.execute("SELECT id FROM puzzle_users WHERE name =?",(username))
sqlite3.ProgrammingError: Incorrect number of bindings supplied
The current statement uses 1, and there are 3 supplied.
There is an error in this line:
cur.execute("SELECT id FROM puzzle_users WHERE name =?",(username))
When you use 1-item tuple you should add a comma before the closing bracket:
cur.execute("SELECT id FROM puzzle_users WHERE name = ?", (username,))
Otherwise (username) is just a string, not tuple.
cursor.execute('UPDATE emp SET name = %(name)s',{"name": name} where ?)
I don't understand how to get primary key of a particular record.
I have some N number of records present in DB. I want to access those record &
manipulate.
Through SELECT query i got all records but i want to update all those records accordingly
Can someone lend a helping hand?
Thanks in Advance!
Table structure:
ID CustomerName ContactName
1 Alfreds Futterkiste
2 Ana Trujillo
Here ID is auto genearted by system in postgres.
I am accessing CustomerName of two record & updating. So here when i am updating
those record the last updated is overwrtited in first record also.
Here i want to set some condition so that When executing update query according to my record.
After Table structure:
ID CustomerName ContactName
1 xyz Futterkiste
2 xyz Trujillo
Here I want to set first record as 'abc' 2nd record as 'xyz'
Note: It ll done using PK. But i dont know how to get that PK
You mean you want to use UPDATE SQL command with WHERE statement:
cursor.execute("UPDATE emp SET CustomerName='abc' WHERE ID=1")
cursor.execute("UPDATE emp SET CustomerName='xyz' WHERE ID=2")
This way you will UPDATE rows with specific IDs.
Maybe you won't like this, but you should not use autogenerated keys in general. The only exception is when you want to insert some rows and do not do anything else with them. The proper solution is this:
Create a sequencefor your table. http://www.postgresql.org/docs/9.4/static/sql-createsequence.html
Whenever you need to insert a new row, get the next value from the generator (using select nextval('generator_name')). This way you will know the ID before you create the row.
Then insert your row by specifying the id value explicitly.
For the updates:
You can create unique constraints (or unique indexes) on sets of coulmns that are known to be unique
But you should identify the rows with the identifiers internally.
When referring records in other tables, use the identifiers, and create foreign key constraints. (Not always, but usually this is good practice.)
Now, when you need to updatea row (for example: a customer) then you should already know which customer needs to be modified. Because all records are identified by the primary key id, you should already know the id for that row. If you don't know it, but you have an unique index on a set of fields, then you can try to get the id. For example:
select id from emp where CustomerName='abc' -- but only if you have a unique constraing on CustomerName!
In general, if you want to update a single row, then you should NEVER update this way:
update emp set CustomerName='newname' where CustomerName='abc'
even if you have an unique constraint on CustomerName. The explanation is not easy, and won't fit here. But think about this: you may be sending changes in a transaction block, and there can be many opened transactions at the same time...
Of course, it is fine to update rows, if you intention is to update all rows that satisfy your condition.
I have a table using SQL Lite with Python. The size of the table always has 3 columns and could have many rows. Each of the cells are strings. Here is example table:
serial_num date_measured status
1234A 1-1-2015 passed
4321B 6-21-2015 failed
1423C 12-25-2015 passed
......
My program prompts me for a serial number. This is saved as a variable called serialNum. How can I delete (or overwrite) an entire row if serialNum equals any of the strings in the serial_num column in my table?
I've seen many examples on how to delete (or overwrite) a row in a table if I know all the values in each cell of that row, but my trouble is that the only cell that could ever be the same in each row would be the serial number. I need to so a search through the serial_number column and if any string in that column equals the current value of my serialNum variable, I need to delete (or overwrite) that row.
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE test (serial_num text, date_measured text, status text)''')
c.execute("INSERT INTO test VALUES ('1234A', '1-1-2015', 'passed')")
c.execute("INSERT INTO test VALUES ('4321B', '6-21-2015', 'failed')")
c.execute("INSERT INTO test VALUES ('1423C', '12-25-2015', 'passed')")
conn.commit()
Does anyone know a simple way to do this? I've seen others say that an ID must be used or a temporary table, but I would hope there might be an easier way to accomplish my task. Any advice would be great.
SQL suports this: simply use delete
"delete from test where serial_num=<some input>;"
or in this case
c.execute("delete from test where serial_num=%s;", serialNum);
There's no need to search through the list when using SQL. SQL is declarative: you tell it what to do using your query, not how to do it. Don't loop though all your rows to check which to delete: tell it what to delete and the database engine will find the best/fastest way to satisfy that goal.
Hope I well interpreted your question
for row in c.execute('SELECT * FROM test WHERE serial_num = ?', serialNum'):
# do whatever you want on row
print row
I was able to figure out a working solution:
sql = "DELETE FROM test WHERE serial_num = ?"
c.execute(sql, (serialNum,))
The comma after serialNum for some reason has to be there. Thank you #Michiel Arienfor the head start
I have a mysql table with coloumns of name, perf, date_time . How can i retrieve only the most recent MySQL row?
As an alternative:
SELECT *
FROM yourtable
WHERE date_and_time = (SELECT MAX(date_and_time) FROM yourtable)
This one would have the advantage of catching the case where multiple rows were inserted very quickly and ended up with the same timestamp.
SELECT * FROM table ORDER BY date, time LIMIT 1
...
ORDER BY `date and time` DESC
LIMIT 1
Note this is not the most recently added row, this is the row with the most "recent" value in the date and time column, which is what I assume you are looking for.
SELECT name,
perf,
date_and_time
FROM table
ORDER BY date_and_time DESC
LIMIT 1
Are date and time separate fields? And would you explain what you mean by "most recent"? If date and time are separate fields or are not refererring to user activity and you mean "most recently updated by user" than you might want to know that time-sensitive tables usually contain a field like "updated_at" which carry a mysql standard timestamp, e.g. '1989-11-09 12:34:32'. Perhaps you should consider introducing a field like this into your schema. You could than set triggers to update the datetime information like so:
CREATE TRIGGER mytable_update BEFORE UPDATE ON `mytable`
FOR EACH ROW SET NEW.updated_at = NOW();
Of course you could than retrieve the record which has been updated most recently by a select statement as answered above:
ORDER BY `updated_at` DESC LIMIT 1;
In addition, time-sensitive tables usually have a field 'created_at' which carries an unchanging timestamp set when the row is inserted. It is often connected to a trigger like so:
CREATE TRIGGER mytable_create BEFORE INSERT ON `mytable`
FOR EACH ROW SET NEW.created_at = NOW(), NEW.updated_at = NOW();
The first trigger above should reflect this and carry the created_at information with an additional statement:
NEW.created_at = OLD.created_at;
If you use a framework (like Django, as you tagged Python), this could be handled by the ORM.
select top 1 * from tablename order by date_and_time DESC (for sql server)
select * from taablename order by date_and_time DESC limit 1(for mysql)
I have a database containing a list of status updates and time stamp.
by executing the following python script
import sqlite3 as lite
import sys
con = lite.connect('Status.db')
with con:
cur = con.cursor()
cur.execute("SELECT * FROM Status")
print "The Status database now contains:"
for row in cur:
print row
results in the output:
The Status database now contains:
(1333155451.8815, u'message')
(1333155469.205055, u'message1')
(1333155473.496727, u'message2')
However, as the database grows, i wish to only view the latest, say, 10 messages. With the option of viewing older messages.
Could anyone give me some tips on how i would go about doing that?
Thanks
You can use ORDER BY and LIMIT, aod use the DESC keyword to show in reverse timestamp order:
SELECT * FROM <yourtable> ORDER BY <timestampcol> DESC LIMIT 10
(For future reference: When you're asking about how to query your data, you should post information about your schema, like table names, column names, and datatypes. It makes it much easier to post an answer containing the actual query.)
Look at ORDER BY and LIMIT clausuls. Those should do the trick :)