0

In my use case, I have a csv stored as a string and I want to load it into a MySQL table. Is there a better way than saving the string as a file, use LOAD DATA INFILE, and then deleting the file? I find this answer but it's for JDBC and I haven't find a Python equivalent to it.

1
  • 1
    Why not just put an insert stmt together ? Commented Jul 22, 2016 at 17:59

1 Answer 1

0

Yes what you describe is very possible! Say, for example, that your csv file has three columns:

import MySQLdb
conn = MySQLdb.connect('your_connection_string')
cur = conn.cursor()
with open('yourfile.csv','rb') as fin:
    for row in fin:
        cur.execute('insert into yourtable (col1,col2,col3) values (%s,%s,%s)',row)
cur.close(); conn.close()
Sign up to request clarification or add additional context in comments.

1 Comment

Will this be slow if I have many rows in my csv? I heard that LOAD DATA INFILE is more efficient when loading a large amount of data.

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.