Giorgos Komnino
Giorgos Komnino

Reputation: 443

Execute bulk insert with sqlalchemy and mysql

I am creating dynamically a bulk insert query. In my application I use sqlAlchemy and I would like to execute that insert.

The problem lies when I am creating the query. I want to insert data that contain special characters that should be escaped.

Using MysqlDb module there is a function MySQLdb.escape_string that escapes the special characters but unfortunately does not work for Unicode characters.

What are my options?

I want to notice that it is not easy to create the query as

q = INSERT INTO table (a, b) VALUES (:a1, :b1), (:a2, :b2) 
q_dict = {(a1, b1), (a2, b2)}

so I can execute Session.execute(q, q_dict) .

Is there a python function that accepts a string and escapes all characters that need escapting for Mysql?

Imagine that I want to create write a file to disk and then execute it through mysql console.

Upvotes: 0

Views: 793

Answers (1)

Giorgos Komnino
Giorgos Komnino

Reputation: 443

Here is the solution :

First get a DBAPi connection

 connection = engine. raw_connection()

And then you can escape the string v using:

 connection.escape(v)

Upvotes: 1

Related Questions