# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
from com.ziclix.python.sql import zxJDBC

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)

qparam = lambda n : '?'

with zxJDBC.connect('jdbc:mysql://localhost:3306/test', 'root', '', 'com.mysql.jdbc.Driver') as con:
    test('MySQL', con, qparam)
with zxJDBC.connect('jdbc:db2://localhost:50000/test', 'arne', 'xxxxxx', 'com.ibm.db2.jcc.DB2Driver') as con:
    test('DB2', con, qparam)
with zxJDBC.connect('jdbc:oracle:thin:@localhost:1521:xe', 'arne', 'xxxxxx', 'oracle.jdbc.OracleDriver') as con:
    test('Oracle', con, qparam)
