# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import pymysql
import psycopg2
import cx_Oracle
import pymssql
import pyodbc

def t1_get_one(con, f2, pnam):
    with con.cursor() as c:
        c.execute('SELECT f1 FROM t1 WHERE f2 = ' + pnam(1), (f2,))
        f1 = c.fetchone()[0]
    return f1

def t1_get_all(con):
    with con.cursor() as c:
        c.execute('SELECT f1,f2 FROM t1')
        res = c.fetchall()
    return res

def t1_put(con, f1, f2, pnam):
    with con.cursor() as c:
        c.execute('INSERT INTO t1(f1,f2) VALUES(' + pnam(1) + ',' + pnam(2) + ')', (f1, f2))

def t1_remove(con, f1, pnam):
    with con.cursor() as c:
        c.execute('DELETE FROM t1 WHERE f1 = ' + pnam(1), (f1,))

def t1_display(data):
    for row in data:
        print('%d %s' % (row[0], row[1]))

def test(lbl, con, pnam):
    print(lbl + ':')
    f1 = t1_get_one(con, 'BB', pnam)
    print(f1)           
    data = t1_get_all(con)
    t1_display(data)
    t1_put(con, 999, 'XXX', pnam)
    data = t1_get_all(con)
    t1_display(data)
    t1_remove(con, 999, pnam)
    data = t1_get_all(con)
    t1_display(data)

cparam = lambda n : '%s'
qparam = lambda n : '?'
nparam = lambda n : ':p' + str(n)

con = pymysql.connect(host='localhost',user='root',password='',db='Test') # pymysql with return a cursor nor a connection
test('MySQL', con, cparam)
con.close()
with psycopg2.connect('host=localhost port=5432 dbname=Test user=postgres password=xxxxxx') as con:
    test('PostgreSQL', con, cparam)
with cx_Oracle.connect('arne/xxxxxx@localhost:1521/xe') as con:
    test('Oracle', con, nparam)
with pymssql.connect(server='ARNEPC4\SQLEXPRESS', database='Test') as con:
    test('SQLServer', con, cparam)
with pyodbc.connect('DSN=ARNEPC4_SQLSRV;UID=;PWD=') as con:
    test('ODBC DSN SQLserver', con, qparam)
with pyodbc.connect('DSN=ARNEPC4_MYSQL;UID=root;PWD=') as con:
    test('ODBC DSN MySQL', con, qparam)
with pyodbc.connect('DSN=ARNEPC4_DB2;UID=arne;PWD=xxxxxx') as con:
    test('ODBC DSN DB2', con, qparam)
with pyodbc.connect('Driver={SQL Server Native Client 11.0};Server=localhost;Database=Test;Trusted_Connection=yes;') as con:
    test('ODBC DSNless SQLserver', con, qparam)
with pyodbc.connect('Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=Test;User=root;Password=;') as con:
    test('ODBC DSNless MySQL', con, qparam)
with pyodbc.connect('Driver={IBM DB2 ODBC DRIVER};Hostname=localhost;Database=Test;Uid=arne;Pwd=xxxxxx;') as con:
    test('ODBC DSNless DB2', con, qparam)
