MySQL 용 이스케이프 문자열 Python
저는 Python과 MySQLdb를 사용하여 웹 페이지를 다운로드하고 데이터베이스에 저장합니다. 내가 가진 문제는 복잡한 문자열이 제대로 이스케이프되지 않아 데이터베이스에 저장할 수 없다는 것입니다.
MySQL의 문자열을 이스케이프하는 데 사용할 수있는 Python 함수가 있습니까? '''
(단순 따옴표 세 개) 및을 사용해 보았지만 """
작동하지 않았습니다. 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()
sqlescapy 패키지 설치 :
pip install sqlescapy
그러면 원시 쿼리에서 변수를 이스케이프 할 수 있습니다.
from sqlescapy import sqlescape
query = """
SELECT * FROM "bar_table" WHERE id='%s'
""" % sqlescape(user_input)
{!a}
적용 ascii()
되므로 따옴표 및 이모티콘과 같은 비 ASCII 문자를 이스케이프합니다. 다음은 예입니다.
cursor.execute("UPDATE skcript set author='{!a}',Count='{:d}' where url='{!s}'".format(authors),leng,url))
참고 URL : https://stackoverflow.com/questions/3617052/escape-string-python-for-mysql
'Program Tip' 카테고리의 다른 글
디렉토리가 git 제어하에 있는지 확인 (0) | 2020.11.23 |
---|---|
세션 변수로 배열 (0) | 2020.11.23 |
iOS에서 언제 setNeedsDisplay를 호출해야합니까? (0) | 2020.11.23 |
해결되지 않은 외부 기호 "public : virtual struct QMetaObject const * __thiscall Parent (0) | 2020.11.22 |
런타임에서 제약 조건 우선 순위를 어떻게 변경할 수 있습니까? (0) | 2020.11.22 |