programing

InterfaceError(0, ')

yoursource 2022. 12. 21. 23:10
반응형

InterfaceError(0, ')

저는 Django를 사용하여 사이트를 구축했는데 쿼리를 실행하려고 하면 이 귀찮은 오류가 발생합니다.

Apache 서버를 재시작하면 오류가 잠시 사라집니다.

Traceback:
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
100.                     response = callback(request, *callback_args, **callback_kwargs)
File "/home/fran/cron/views/set_caches.py" in set_caches
24.         cursor.execute(query, [category['id']])
File "/usr/local/lib/python2.7/site-packages/django/db/backends/util.py" in execute
15.             return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py" in execute
86.             return self.cursor.execute(query, args)
File "build/bdist.linux-i686/egg/MySQLdb/cursors.py" in execute
155.         charset = db.character_set_name()

Exception Type: InterfaceError at /blablabla/
Exception Value: (0, '')

이는 글로벌 커서가 원인입니다.원시 쿼리가 필요한 각 메서드 내에서 커서를 만들고 닫아 보십시오.

cursor = connection.cursor()
cursor.execute(query)
cursor.close()

이 에러가 발생하는 것은,db.close()를 호출하고 나중에 새로운 접속을 작성하지 않고 데이터베이스에 접속을 시도합니다.의도하지 않을 때 데이터베이스에 대한 연결을 닫았는지 확인합니다.

나는 Moberg의 의견에 동의해.이 오류는 접속을 종료한 후 데이터베이스에 접속하려고 할 때 발생합니다.이 문제는 코드의 잘못된 들여쓰기가 원인일 수 있습니다.아래는 제 코드입니다.

conn = connect()
cur = conn.cursor()
tk = get_tickers(cur)
for t in tk:
    prices = read_price(t, cur)
    if prices != None:
        update_price(t, cur)
        print 'Price after update of ticker ', t, ':'
        p_open, p_high, p_low, p_close = read_price(t, cur)
        print p_open, p_high, p_low, p_close
    else:
        print 'Price for ', t, ' is not available'
    conn.close()

마리안이 보고한 것과 같은 오류가 발생했습니다.conn.close()를 지정하면 모든 것이 정상적으로 동작했습니다.global conn이 문제가 아님을 확인.

Python 3.7과 Mysql 2.7을 사용한 2019년 4월과 같은 문제가 있었습니다.

간헐적으로 문자열(0, ')이 SQL 문에 랜덤으로 추가되어 오류가 발생합니다.데이터베이스 접속의 종료에 대해 코멘트를 하고, 커서의 종료는 코드에 남겨 두는 것으로 문제를 해결했습니다.

def set_db():
    db = pymysql.connect(host='localhost',
                         user="root",
                         passwd="root",
                         db="DATABASE")
    return db


def execute_sql(cnx, sql_clause, fetch_all):

    if sql_clause and sql_clause is not None:
        try:
            cnx.execute(sql_clause)
        except Exception as e:
            print("Error in sql: " + sql_clause + str(e))
            return 0
            pass

        if fetch_all:
            result = cnx.fetchall()
        else:
            result = cnx.fetchone()

        return result
    else:
        print("Empty sql.")
        return 0

db = set_db()
cnx = db.cursor()
sql = "SELECT * FROM TABLE"
result = execute_sql(cnx, sql, 1)
cnx.close() #close the cursor
#db.close #do not close the db connection

...

글로벌 커서가 원인이 되어 나중에 일부 기능에서 사용되는 것을 확인할 수 있습니다.증상은 동일했습니다.Apache 재기동에 의해 일시적으로 해소되는 간헐적인 인터페이스 에러입니다.

from django.db import connection
cursor = connection.cursor() # BAD

def foo():
    cursor.execute('select * from bar')

하지만 Oracle 11.2에서 Django를 사용하고 있기 때문에 MySQL/python 드라이버의 버그는 아닌 것 같습니다.이는 apache/mod_wsgi에 의한 캐시 때문일 수 있습니다.

Python3와 Pymysql의 스레드 사용에서도 같은 문제가 있었습니다.교착 상태가 되어 InterfaceError(0, ')가 발생하였습니다.

문제는 쿼리를 제외하고 롤백을 실행하려고 했다는 것입니다.이 롤백은 존재하지 않는 연결을 사용하려고 하고 인터페이스 오류를 발생시킨 것 같습니다.이 롤백을 꺼내고(이 쿼리는 롤백을 하지 않아도 괜찮기 때문에) 그냥 넘어갑니다.이것으로 문제가 해결되었습니다.

def delete_q_msg(self, assetid, queuemsgtypeid, msgid):
    """
    Given the paramerts below remove items from the msg queue equal to or older than this.
    If appropriate send them into a history table to be processed later

    :param assetid:
    :param queuemsgtypeid:
    :param msgid:
    :return:
    """
    params = (assetid, queuemsgtypeid, msgid,)
    db_connection = self._connect_to_db()
    sp_sql = "{db}.ps_delete_q_msg".format(db=self._db_settings["database"])
    return_value = []
    try:
        with db_connection.cursor() as cursor:
            cursor.callproc(sp_sql, params)
            return_value = cursor.fetchall()
        db_connection.commit()
    except Exception as ex:
        # i think we dont want rollback here
        # db_connection.rollback()
        raise Exception(ex)
    finally:
        db_connection.close()

    return return_value

Flask그 Flask+pymysql에 빈 .그 결과 빈 태플이 생겼습니다.except:, 것"(\"(0, '')\",)"체적적구

이 에러는, 접속이 종료되고 나서 코드가 접속을 시도하고 있는 것을 알 수 있었습니다. 저는 을 참고하여 하였고, 연결 을 사용하였습니다.conn「 DB 」 「DB」

하려면 , 「」를 삽입해 주세요.conn.close() 하기 위해서cursor.

참고로 이 사이트를 사용하여 이 문제를 해결했습니다.

https://hackersandslackers.com/python-mysql-pymysql/

★★★를 conn.close()제 직능에서요.닫은 후 다시 데이터베이스에 접속하려고 했습니다.AWS aws aws aws aws aws aws aws aws aws aws aws aws aws aws aws aws aws aws aws 。또한 플라스크 어플리케이션이 오래 실행 중이고, 저와 같이 MYSQL 워크벤치와 함께 AWS RDS를 사용하고 있다면 세션이 만료되었는지 확인하고 액세스 키와 ID를 업데이트해 보십시오.

이게 도움이 됐으면 좋겠다.

나도 같은 문제가 있었고, 장고에서 나에게 효과가 있었던 것은 다음과 같은 내용으로 구성된 이 답변에 기술되어 있다.

교환

'ENGINE': 'django.db.backends.mysql'

와 함께

'ENGINE': 'mysql_server_has_gone_away'

settings.DATABASES['ENGINE']

다음 패키지를 pip으로 설치합니다.

mysql_server_has_gone_away==1.0.0
with connections.cursor() as cursor:
    res=cursor.execute(sql)

언급URL : https://stackoverflow.com/questions/6650940/interfaceerror-0

반응형