"""showpix.py -- display a .jpg image from database with key = argv[1]
call using "showpix.py N" where N is the Codigo number of the image to display.

version 0.0 2011-02-17 by Vernon Cole - vernondcole@gmail.com 
"""
#Expects Python version 2.6 or later from http://python.org
#  and a matching pywin32 from http://sourceforge.net/projects/pywin32
#  and adodbapi version 2.4.2 or later from http://sourceforge.net/projects/adodbapi

from __future__ import print_function
import sys
import os
#---------------------------------------------
#subroutine to create a binary file 
def showpic(fname,buf):
    with open(fname,'wb') as outfile:
        outfile.write(buf)
    print('wrote file:',fname)
    os.startfile(fname) # show the image using default viewer
# -------------- main program starts here -------------------------------
if __name__ == '__main__':
    import adodbapi
    constr = "Provider=SQLOLEDB.1; Integrated Security=SSPI; Initial Catalog={db};Data Source={dbsrvr}"
    s = constr.format(dbsrvr='(local)', db='Imagenes')
    adodbapi.adodbapi.verbose = True # for debugging output

    key = sys.argv[1]  # key number of picture to view

    con = adodbapi.connect(s)           # connect to the db server
    c = con.cursor()                    # open a cursor on the connection
    sql = 'select Foto, Descripcion from Fotos where Codigo = ?'
    c.execute(sql,[key])
    row = c.fetchone()
    if row:
        print('Foto de:',row.Descripcion)
        showpic('x.jpg',row.Foto)
    else:
        print('"%s" Not found'% key)
    c.close()
    conn.close()
    