开发者

python - need help inserting text files with open() into mysql

开发者 https://www.devze.com 2023-01-20 05:22 出处:网络
Can someone h开发者_运维问答elp me out with the mysql connection statement to instert a textfile into a mysql table (field type is long blob)?

Can someone h开发者_运维问答elp 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?


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(), ))
0

精彩评论

暂无评论...
验证码 换一张
取 消