programing

이스케이프 문자열 Python for MySQL

firstcheck 2023. 1. 1. 11:39
반응형

이스케이프 문자열 Python for MySQL

Python과 MySQLdb를 사용하여 웹 페이지를 다운로드하여 데이터베이스에 저장합니다.문제는 복잡한 문자열이 제대로 이스케이프되지 않아 데이터베이스에 저장할 수 없다는 것입니다.

Python에서 MySQL용 문자열을 이스케이프할 수 있는 함수가 있나요?로 시도했다.'''(단순한 따옴표 표시) 및""",하지만 그것은 작동하지 않았다.나는 PHP가 다음을 가지고 있다는 것을 안다.mysql_escape_string()Python에서도 비슷한가요?

감사해요.

conn.escape_string()

MySQL C API 함수 매핑을 참조하십시오.http://mysql-python.sourceforge.net/MySQLdb.html

MySQLdb 라이브러리는 실제로 구현을 사용하여 SQL 쿼리 문자열을 작성하는 대신 이를 수행합니다.

실행 안 함:

sql = "INSERT INTO TABLE_A (COL_A,COL_B) VALUES (%s, %s)" % (val1, val2)
cursor.execute(sql)

작업:

sql = "INSERT INTO TABLE_A (COL_A,COL_B) VALUES (%s, %s)"
cursor.execute(sql, (val1, val2))
>>> import MySQLdb
>>> example = r"""I don't like "special" chars ¯\_(ツ)_/¯"""
>>> example
'I don\'t like "special" chars \xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf'
>>> MySQLdb.escape_string(example)
'I don\\\'t like \\"special\\" chars \xc2\xaf\\\\_(\xe3\x83\x84)_/\xc2\xaf'

sqlalchemy의 텍스트 함수를 사용하여 특수 문자의 해석을 제거합니다.

기능의 사용법에 주의해 주세요.text("your_insert_statement")아래. 전달된 문자열에 있는 모든 물음표와 백분율 기호가 리터럴로 간주되어야 한다는 것을 sqlalchemy에 전달하는 것입니다.

import sqlalchemy
from sqlalchemy import text
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import re

engine = sqlalchemy.create_engine("mysql+mysqlconnector://%s:%s@%s/%s"
     % ("your_username", "your_password", "your_hostname_mysql_server:3306",
     "your_database"),
     pool_size=3, pool_recycle=3600)

conn = engine.connect()

myfile = open('access2.log', 'r')
lines = myfile.readlines()

penguins = []
for line in lines:
   elements = re.split('\s+', line)

   print "item: " +  elements[0]
   linedate = datetime.fromtimestamp(float(elements[0]))
   mydate = linedate.strftime("%Y-%m-%d %H:%M:%S.%f")

   penguins.append(text(
     "insert into your_table (foobar) values('%%%????')"))

for penguin in penguins:
    print penguin
    conn.execute(penguin)

conn.close()

이 문제를 해결하기 위한 또 다른 방법은 파이썬에서 mysqlclient를 사용할 때 이와 같은 방법을 사용하는 것입니다.

입력하려는 데이터가 다음과 같다고 가정합니다.<ol><li><strong style="background-color: rgb(255, 255, 0);">Saurav\'s List</strong></li></ol>. 이중 Qoute와 단일 따옴표가 모두 포함되어 있습니다.

다음 방법을 사용하여 따옴표를 이스케이프할 수 있습니다.

스테이트먼트 = ""채팅 업데이트 세트 html='{}' ".format (format_string.replace"",\\"")

주의: 포맷되지 않은 python 문자열에 포함된 단일 따옴표를 이스케이프하려면 3개의 \ 문자가 필요합니다.

sqlescapy 패키지 설치:

pip install sqlescapy

그러면 원시 쿼리에서 변수를 이스케이프할 수 있습니다.

from sqlescapy import sqlescape

query = """
    SELECT * FROM "bar_table" WHERE id='%s'
""" % sqlescape(user_input)

{!a}적용하다ascii()따라서 비 ASC를 탈출합니다.따옴표나 이모티콘 같은 글자들.여기 예가 있습니다.

cursor.execute("UPDATE skcript set author='{!a}',Count='{:d}' where url='{!s}'".format(authors),leng,url))

Python3 문서

언급URL : https://stackoverflow.com/questions/3617052/escape-string-python-for-mysql

반응형