python DB API - taoualiw/My-Knowledge-Base GitHub Wiki

Python DB-APIs

The Python DB-API isnot the library. It is a standard for Python libraries that let's your code connect to databases.

Database System DB-API module
SQLite sqlite3
PostgreSQL psycopg2
ODBC pyodbc
MySQL mysql.connector

Examples of Python DB-API Library use:

import sqlite3
conn = sqlite3.connect("Cookies")
cursor = conn.cursor()
cursor.execute("select host_key from employees limit 10")
results = cursor.fetchall()
print(results)
conn.close()
import psycopg2
pg = psycopg2.connect("db_name")
c = pg.cursor()
c.execute("insert into names values ('Jane Austin')")
pg.commit()

- Common Problems:

see docs for more details

  • SQL Injection Attack: Database entries interpreted as SQL commands:
    • example : if content = '); delete from posts; --' then
       c.execute("insert into posts values ('%s')" % content)
      deletes all the rows is the posts table
    • solution:
    c.execute("insert into posts values (%s)", (content,))
    • summary: Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.
  • Script Injection Attack: Browser interpreting entries/text as a piece of code
    • solution : use python library bleach
  • Bad entries :
    • solution : update table by replacing the bad entries with some neutral text or deleting
    update table set column = value where column like  'badword%' ;
    delete from table where column like  'badword%' ;

Debugging

  • Error when running python code to connect to database: -message :
      Is the server running locally and accepting
      connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
    • solution :
    - postgres -D /usr/local/var/postgres
    - pg_ctl -D /usr/local/var/postgres start
⚠️ **GitHub.com Fallback** ⚠️