import MySQLdb
import re
def write():
file = open('/home/fixstream/Desktop/test10.txt', 'r')
print file.read()
file.close()
write()
Run Code Online (Sandbox Code Playgroud)
我上面的代码,现在我想将文本文件存储到mysql数据库中.我是python以及数据库的新手.所以任何人都可以帮助我吗?
我建议你阅读这个MySQLdb教程.首先,您需要将文件的内容存储在变量中.然后它只是连接到您的数据库(这可以在链接中看到),然后执行INSERT查询.准备好的语句与 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()
Run Code Online (Sandbox Code Playgroud)
注意file_content之后的逗号 - 这确保execute()的第二个参数是一个元组.另请注意db.commit()确保编写更改.
如果您需要进一步解释,请询问.
| 归档时间: |
|
| 查看次数: |
12003 次 |
| 最近记录: |