0
0
0ralo2020-04-14 19:16:19
MySQL
0ralo, 2020-04-14 19:16:19

How to work with pymysql?

Hello, I have a question that is quite difficult to state correctly. I don’t understand how I can effectively work with Pymysql in python. I know the python syntax well, mysql is worse, but I can work. But at work I have a lot of problems with the type of data loading in db. I had a project with which I started learning python, it was a bot on vk. There I used Json as a db, that is, Json with user data was next to the executable file, I opened it in code, read / wrote and saved. Naturally, this is not entirely correct, because you can make queries to the database and get the information I need, but I ran into some problems. The most incomprehensible of them is saving different data types:

def setdigit(self, id, data):
    with self.connect:
      cur = self.connect.cursor()
      cur.execute(f"UPDATE DB.USERS SET {data.keys()[0]}={data[data.leys()[0]]} WHERE id={id}")

  def setstring(self, id, data):
    with self.connect:
      cur = self.connect.cursor()
      cur.execute(f"UPDATE DB.USERS SET {data.keys()[0]}='{data[data.leys()[0]]}' WHERE id={id}")

I pass the required ID and {"Key":"value"} to the function.
And every time I need to call the function for writing a number or a string, it's not very convenient, I also don't really understand how to load data into the database from python correctly. If you do a function that takes all arguments separately:
def setdigit(self, id, key, value):
    with self.connect:
      cur = self.connect.cursor()
      cur.execute(f"UPDATE DB.USERS SET {key}={value} WHERE id={id}")

Then, of course, calling such a function becomes more grammatical, although perhaps it’s more correct. In general, can you explain how to work more correctly, and ideally attach a piece of code from production where pymysql is used so that I understand how to connect python and database. Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Victor, 2020-04-14
@0ralo

You can look at MongoDB . It just has JSON-like documents, and in MySQL it's better not to store data like that.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question