enf644
enf644

Reputation: 584

Sqlalchemy core - dynamic SQL query and escaping values

I’m creating a dynamic Insert query.

    sql = "INSERT INTO `" + self.db_name + "` ("
    sql += ','.join(e.db_name for e in self.fields)
    sql += ") VALUES ("
    sql += ','.join(("'" + e.value + "'") for e in self.fields)
    sql += ");"
    result = s.execute(sql)

It works fine, except the inserted value is not safe of special characters and SQL injection.

I cant use the SqlAlchemy text() mechanism because i don’t know the names or quantity of fields in table.

I tryed MySQLdb.escape_string(), but its not working with Unicode.

How can i make a dynamic sql Insert query while escaping special characters in unicode value?

Upvotes: 4

Views: 2537

Answers (1)

enf644
enf644

Reputation: 584

The answer I wanted to hear 4 years ago -

sql = 'INSERT INTO some_table (guid, name) VALUES (:guid_val, :name_val)'

db_session.execute(sql, {
  "guid_val": uuid.uuid4(),
  "name_val": "Hello world"
})

Upvotes: 5

Related Questions