如何使用python将文本文件存储到MySQL数据库中
import MySQLdb
import re
def write():
file = open('/home/fixstream/Desktop/test10.txt', 'r')
print file.read()
file.close()
write()
我有上面的代码,现在我想将文本文件存储到 mysql db 中.我是 python 和数据库的新手.所以有人可以帮我解决这个问题吗?
Above code i have, now i want to store the text file into mysql db. I am new to python as well as database. So anyone can help me with this?
我建议你阅读这个 MySQLdb 教程.首先,您需要将文件内容存储在变量中.然后它只是连接到您的数据库(如您在链接中看到的那样),然后执行 INSERT 查询.准备好的语句以类似的方式完成蟒蛇.
I suggest you reading this MySQLdb tutorial. First, you need to store content of the file in a variable. Then it's simply connecting to your database (which is done as you can see in the link) and then executing INSERT query. Prepared statements are done in similar way as common string formatting in python.
你需要这样的东西:
import MySQLdb
db = MySQLdb.connect("localhost","user","password","database")
cursor = db.cursor()
file = open('/home/fixstream/Desktop/test10.txt', 'r')
file_content = file.read()
file.close()
query = "INSERT INTO table VALUES (%s)"
cursor.execute(query, (file_content,))
db.commit()
db.close()
注意 file_content 后面的逗号 - 这确保了 execute() 的第二个参数是一个元组.还要注意确保写入更改的 db.commit().
Note the comma after file_content - this ensures the second argument for execute() is a tuple. Also note db.commit() which ensures writing changes.
如果您需要进一步解释,请询问.
If you need further explanation, ask.