如何使用python将文本文件存储到MySQL数据库中 [英] How to store text file into MySQL database using python

查看:125
本文介绍了如何使用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.

这篇关于如何使用python将文本文件存储到MySQL数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆