4

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?

2
  • This is wrong approach if you indent to use SQLAlchemy. Do you have SQLAlchemy model classes? You can use them dynamically. If you don't you can also generate SQLAlchemy models in-fly: docs.sqlalchemy.org/en/rel_1_0/orm/extensions/automap.html Commented Aug 6, 2015 at 13:44
  • You'd possibly use table() and column(), the light weight analogues of Table and Column, but this reeks of an XY problem. Why would one not know the names of their tables etc.? Commented Apr 3, 2018 at 11:43

1 Answer 1

5

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" }) 
Sign up to request clarification or add additional context in comments.

2 Comments

Can you elaborate why this is the correct approach? Is this like prepared statements for Sqlalchemy? Is this the same as values = {"guid_val": uuid.uuid4(), "name_val": "Hello World"} sql = some_table.insert() sql.insert({**values}) using sqlalchemy core?
If you want to make simple INSERT - using sql.insert() is better then my answer. My question 4 years ago was about constructing safe custom queries with many unknowns. The main problem is SQL injection. Using parameterized execution is far safer than just constructing a SQL string with values and executing it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.