mercredi 2 mai 2018

Python - Check if an entry already exists in a sql database? [on hold]

I have some code that goes out to a SQL DB .. then runs a SELECT and looks for a particular name, If found i want it to write to a file .. however if not found i want it to write to the same file missing

Here is the code i have but i can't get it to work for me

#! /usr/bin/python

import sys, pymssql, string, os, calendar, datetime, traceback, socket, platform
sys.path.insert(0, '/opt/pass')
from pass import password

try:
        d = datetime.datetime.now()
        log = open("pass/LogFile.txt","a")
        log.write("----------------------------" + "\n")
        log.write("----------------------------" + "\n")
        log.write("Log: " + str(d) + "\n")
        log.write("\n")

        starttime = datetime.datetime.now()
        log.write("Begin process:\n")
        log.write("     Process started at "
        + str(starttime) + "\n")
        log.write("\n")

        conn = pymssql.connect(
        server="server",
        port=2048,
        user="user",
        password=password,
        database="table")
        conn


        cursor = conn.cursor()
        cursor.execute("SELECT name, address FROM table WHERE name = 'peter'")
        with open('pass/result.txt', 'w') as f:

        data = cursor.fetchall()
        if data is None:
                print ('missing')
        else:
                for row in cursor.fetchall():
                        print ( "This person " + (row[0])),
                        print ( "is from here " + (row[1]))
                f.write(str( "This person " + (row[0])))
                f.write("%s\n" % str( " is from here " + (row[1])))
        conn.close()

        endtime = datetime.datetime.now()

        log.write("     Completed successfully in "
        + str(endtime - starttime) + "\n")
        log.write("\n")
        log.close()
except:
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]

        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info())

        log.write("" + pymsg + "\n")
        log.close()

Aucun commentaire:

Enregistrer un commentaire