0

Can someone help me out with the mysql connection statement to instert a textfile into a mysql table (field type is long blob)?

For example:

cursor.execute("insert into mytable (file_contents) values ('"+open(filename,"r").read()+"')")

Obviously that's not very practical, can someone post a better way to do this?

1 Answer 1

1

It is dangerous to append content of a file directly into an SQL query, because of special characters (quotes!) or malicious SQL commands.

Try this:

with open(filename,"r") as infile:
    cursor.execute("insert into mytable (file_contents) values (%s)", (infile.read(), ))
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly. Note that the data from infile is passed as second argument -- the string interpolation is handled by cursor.execute which also makes sure that the string parameters are correctly escaped.

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.