VA Session 5 Python vs SQL Flashcards

1
Q

SQL vs Python

A

SQL
- to store data & initial processing
- for operations on large datasets (many rows & columns)
- for heavy duty tasks
- limited numbers of built-in functions
- often more efficient (python every time code executed, connects to database again)

Python
- for exploratory & further data analysis
- many built-in functions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Python connecting to database

A
  • supports connecting to common commercial & open-source databases
  • SQL commands
  • Why? -> data often stored in database (not file e.g. csv)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Connecting Python & database - code

A

inport sqlite3
db = sqlite3.connect(“path…”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Querying database with Python - code

A

db.execute(“SELECT … FROM …”).fetchone()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Adding a record to database with Python - code

A

db.execute(“INSERT INTO table(column) VALUES (“…”)”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Return output - code

A
  • fetchall(): retrieves result of query as list where each returned row = tuple
  • fetchone(): retrieves first row of results of query as tuble
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Parameters

A
  • allow feeding values into query
  • e.g. name = input(“Product name: )
  • db.execute(“SELECT ProductPrice FROM Product WHERE ProductName=?”,[name]).fetchone()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Error Handling

A
  • prevent if query fails, script continues running
  • One approach: try & except
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

SQL Injections: Danger

A
  • Threat when application connected to database (e.g. web interfaces: webpages input communicates with a database)
  • unauthorized view or edit data (or whole database)
  • unauthorized inputs (e.g. DROP TABLE Users)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

approaches of calculating most expensive product

A
  • SQL: db.execute(“SELECT Max(ProductPrice) FROM Product”).fetchone()
  • SQL & Python: prices = db.executre(…).fetchall(); mostExpensive = max(prices)
    -1> 2 (2. brings potentially millions of unnecessary data
How well did you know this?
1
Not at all
2
3
4
5
Perfectly