Python Forum
How to save specific variable in for loop in to the database? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to save specific variable in for loop in to the database? (/thread-36598.html)



How to save specific variable in for loop in to the database? - ilknurg - Mar-09-2022

have commands like:

SELECT UserName FROM Win32_ComputerSystem
which gives me the username of computer. or SELECT Manufacturer, Model FROM Win32_ComputerSystem it gives me the manufacturer.

In this part of my code




query = f"select command_line from wmic_commands where id = '{wmic_id}'"
    cursor = connection.cursor(dictionary=True)
    cursor.execute(query)
    command_line = cursor.fetchall()
[b]    for data in command_line:
      cmd_line = data['command_line']
      output = wmic.query(cmd_line)[/b]
      result = json.dumps(output)
      mySql_insert_query = """INSERT INTO wmi_inventory (wmi_data, date) 
                                VALUES (%s, %s) """
      now = datetime.now()
      dt_string = now.strftime("%Y-%m-%d-%H:%M:%S")
      record = (result, dt_string)
      cursor.execute(mySql_insert_query, record)
      connection.commit()
I execute all these queries in my for loop. And save the output as a json data in my database. But i want to save outputs in to the database like when i execute the username commands, save it in to username column.
How can i do it? Im so confused because in my for loop I run all the commands in order.


RE: How to save specific variable in for loop in to the database? - cubangt - Mar-09-2022

Is that your full query?
If you are able to do your select against the same table, in your example = FROM Win32_ComputerSystem

Then you should be able to insert all those values into the DB per loop.

It would be better if you are able to provide a little more code that you are using or trying to better assist..

example i found online..
mycursor = mydb.cursor()

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)

mydb.commit()
I think providing more of your code would help.. im sure its just something that needs to be reorganized so that each loop inserts that set of data values.