Python MySQL escape special characters

前端 未结 4 1753
感动是毒
感动是毒 2020-12-16 05:34

I am using python to insert a string into MySQL with special characters.

The string to insert looks like so:

macaddress_eth0;00:1E:68:C6:09:A0;macadd         


        
4条回答
  •  执念已碎
    2020-12-16 05:53

    Python example how to insert raw text:

    Create a table in MySQL:

    create table penguins(id int primary key auto_increment, msg VARCHAR(4000))
    

    Python code:

    #!/usr/bin/env python
    import sqlalchemy
    from sqlalchemy import text
    
    engine = sqlalchemy.create_engine(
        "mysql+mysqlconnector://yourusername:yourpassword@yourhostname.com/your_database")
    db = engine.connect()
    
    weird_string = "~!@#$%^&*()_+`1234567890-={}|[]\;':\""
    
    sql = text('INSERT INTO penguins (msg) VALUES (:msg)')
    insert = db.execute(sql, msg=weird_string)
    
    db.close()
    

    Run it, examine output:

    select * from penguins
    
    1      ~!@#$%^&*()_+`1234567890-={}|[]\;\':"
    

    None of those characters were interpreted on insert.

提交回复
热议问题