Search code examples
pythonmysql-pythonmysql-error-1064

How to add exception to python function?


Good day. I wrote an application on python that collects call logs from the Avaya PBX and writes them to the mysql database. It works well, but sometimes the PBX sends an empty string for some reason and the program fails. I attach the screen and code below. I understand that you need to wrap the function in an exception: try except, but I don’t understand how to do it. Please tell me how to do this.enter image description here


def write_db(item, *agrs):
    connection = pymysql.connect(host='localhost',
                                 user='acdr',
                                 password='it8ejokd',
                                 db='avaya_cdr',
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)
    DBTBL = "cdr102019"
    DBFLD = "Date_call, Time_call, `Sec_dur`, `clg_num_in_tag`, `dialed_num`, dep_called, dep_dialed"

    dep_num_call = find_dep(item[3].replace(' ', ''))
    name_dep_call = name_dep(dep_num_call)
    dep_num_dial = find_dep(item[4].replace(' ', ''))
    name_dep_dial = name_dep(dep_num_dial)

    item.append(name_dep_call)
    item.append(name_dep_dial)
    item[1] = item[1] + "00"

    try:
        with connection.cursor() as cursor:
            sql = "INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES (%s,%s,%s,%s,%s,%s,%s)"
            cursor.execute(sql, (item))
        connection.commit()
    finally:
        connection.close()

# Задаем адрес сервера
SERVER_ADDRESS = ('', 5100)

# Настраиваем сокет
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(SERVER_ADDRESS)
server_socket.listen(5)
print('server is running, please, press ctrl+c to stop')

# Слушаем запросы и пишем в db
while True:
    connection, address = server_socket.accept()

    data = connection.recv(1024)
    if not(b'\x00\x00\x00' in data) and not(b'1370' in data):
        str = data.decode("utf-8")
        item=[str[0:6],str[7:11],str[12:17],str[18:33],str[34:57]]
        print(item)
        write_db(item)

    connection.close()

Solution

  • You'll have to catch the exception, so we can cater for a few types, but just to be sure and get you up and running, you could do the following :)

    try:
        with connection.cursor() as cursor:
            sql = (
                    "INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES " 
                    "(%s,%s,%s,%s,%s,%s,%s)"
            )
            cursor.execute(
                sql,
                (item),
            )
    
        connection.commit()
    
    except Exception as e:
        print("Error occurred: %s"% e)
    
    finally:
        connection.close()