What is this cur.execute statement doing?

荒凉一梦 提交于 2019-12-12 03:52:29

问题


I am doing a Coursera course, working with Python and SQL databases. The code further below is largely example code from the course. I have to alter it for an assignment.

The part which I do not completely understand is this part:

cur.execute('SELECT count FROM Counts WHERE email = ? ', (email, ))
row = cur.fetchone()
if row is None:
    cur.execute('''INSERT INTO Counts (email, count) VALUES ( ?, 1 )''', 
    ( email, ) )
else : 
    cur.execute('UPDATE Counts SET count=count+1 WHERE email = ?', 
    (email, ))

What I do understand is that the if clause looks if the email address is already there and adds if it is not, and increases the count if it is. However I do not fully understand what it is "SELECTING" and what is is fetching (fetchone). I have some questions about this.

  1. Can someone explain to me intuitively how this part works?

  2. I am normally used to using print statements to see what is happening. Is there a similar approach here that I can use to see what I am doing?

  3. As a last small question in the code ''' is used for the SQL but also a single ' , for example in the first line above (They also give different colours in my Notepad++). Is there any difference between these to?

Note - I am using Python 3.6

# exec(open("./SQLH152.py").read())

import sqlite3
import re

conn = sqlite3.connect('emaildb.sqlite')
cur = conn.cursor()

cur.execute('''
DROP TABLE IF EXISTS Counts''')

cur.execute('''
CREATE TABLE Counts (email TEXT, count INTEGER)''')
fname = input('Enter file name: ')
if ( len(fname) < 1 ) : fname = 'mbox-short.txt'
fh = open(fname)
for line in fh:
    if not line.startswith('From: ') : continue
    pieces = line.split()
    email = pieces[1]
    x = re.findall('@(\S+)', email)
    print (x)
    cur.execute('SELECT count FROM Counts WHERE email = ? ', (email, ))
    row = cur.fetchone()
    if row is None:
        cur.execute('''INSERT INTO Counts (email, count) VALUES ( ?, 1 )''', 
        ( email, ) )
    else : 
        cur.execute('UPDATE Counts SET count=count+1 WHERE email = ?', 
        (email, ))
    # This statement commits outstanding changes to disk each 
    # time through the loop - the program can be made faster 
    # by moving the commit so it runs only after the loop completes
    conn.commit()

# https://www.sqlite.org/lang_select.html
sqlstr = 'SELECT email, count FROM Counts ORDER BY count DESC LIMIT 10'

print ("")
print ("Counts:")
for row in cur.execute(sqlstr) :
    print (str(row[0]), row[1])

cur.close()

来源:https://stackoverflow.com/questions/44617051/what-is-this-cur-execute-statement-doing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!