且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用python将文本文件存储到MySQL数据库中

更新时间:2023-01-21 11:31:41

我建议你阅读这个 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.