J
J
Julia Kovalenko2017-01-13 15:29:08
MySQL
Julia Kovalenko, 2017-01-13 15:29:08

How to query mysql in python3.5?

The problem is this. I am getting json string with data.
I transform it
data= json.loads(response)
I need to interpose these data into a mysql DB.
I'm trying to insert 20 rows in one request.

INSERT INTO table_name (col1, col2, ... col20)
VALUES (...), (...), ...

There are many columns in this table.
Values ​​of different types: int, string, null, bool.
Plus, all the data from json must somehow be escaped / removed tags.
How to humanly make a query string to the database?
While I'm looping through this json. I choose the right values. I combine them with the help of
",".join(...)
But these are crutches ...)
Are there any libraries with methods like insert (). So that they themselves escape the parameters and generate a sql query?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
Julia Kovalenko, 2017-01-16
@kovalenko_jul_s

I solved my problem using MySQLdb.
1. Parsed the json file into a two-dimensional list
2. Formed a query string

query = "INSERT INTO ads_irr_ru_content (col1, col2, .... ,col5) VALUES "  + 
    ",".join("(%s,%s,%s,%s,%s)" for _ in values)

3. Collected the inserted data
4. Inserted data :)
cur.execute(query, flattened_values)

N
newpy, 2017-01-13
@newpy

I'll make out already then instead of comments =)
there are a lot of libraries, but from the last one for working with the database I liked
1. records , its author Kenneth Reitz, the author of the requests library.
2. peewee the second well-known small and somewhat similar to django ORM or Alchemy

A
Alexander Ivanov, 2017-01-13
@zalupadrakona

sql = ('''INSERT INTO users (login, password) VALUES (%s, %s)''')
data = (login, password)

Something like this you can try

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question