-1

I have two list:

run = ['2019-01-03', '2019-01-04', '2019-01-05']
curr = ['2019-01-04', '2019-01-05', '2019-01-06']

i want to insert dates into table vv_flag in columns run_date and curr_date respectively. like:

run_date      curr_date
2019-01-03    2019-01-04
2019-01-04    2019-01-05

query = "select run_date, curr_date from cdedev.vv_flag where flag = 'N'"
ress = cur.execute(query)
print(ress)
result = cur.fetchall()
run = result['run_date']
curr = result['curr_date']
5
  • Possible duplicate of Take multiple lists into dataframe Commented Feb 5, 2019 at 9:46
  • 1
    Please explain it a little bit more. what have you tried till, any code snippet ? Commented Feb 5, 2019 at 9:48
  • i extracted list of dates from a particular table. now i want to insert those dates list into another table like shown above. i'm using insert query to insert dates in columns but how to iterate for whole dates ? Commented Feb 5, 2019 at 9:55
  • 2
    What do you mean "into table"? Are you using an SQL database? the Pandas dataframes? Plain Python lists? Or just what exactly? It would help to see the code you used to extract the dates, that would at least help explain what you are doing.... Commented Feb 5, 2019 at 9:57
  • query = "select run_date, curr_date from cdedev.vv_flag where flag = 'N'" ress = cur.execute(query) print(ress) result = cur.fetchall() run = result['run_date'] curr = result['curr_date'] Commented Feb 5, 2019 at 10:07

1 Answer 1

1

Let's consider you are using mysql. First you have to establish connection. Then you have to iterate through two list in parallel. Then you have to use it along with the query. Always make commits in bulk to reduce time. mydb.commit() It is required to make the changes, otherwise no changes are made to the table.

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
  )

mycursor = mydb.cursor()
run = ['2019-01-03', '2019-01-04', '2019-01-05']
curr = ['2019-01-04', '2019-01-05', '2019-01-06']
for i,j in zip(run,curr):
   query = "insert into vv_flag(run_date,curr_date) values ('{0}','{1}') where flag = 'N'".format(i,j)
   mycursor.execute(query)

mydb.commit()
Sign up to request clarification or add additional context in comments.

1 Comment

You need to get run and curr from his previous query: run, curr = zip(*result)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.