python将本地txt文档存入mysql数据库举例
时间: 2023-06-05 14:08:26 浏览: 81
好的,可以举例说明。您需要先安装PyMySQL模块,然后使用以下代码将文本文件中的数据插入到MySQL数据库中:
```python
import pymysql
# 连接mysql数据库
conn = pymysql.connect(host='localhost',port=3306,user='root',password='password',db='database_name')
cursor = conn.cursor()
# 打开本地的txt文件并读取数据
with open('file.txt', 'r', encoding='utf-8') as file:
data = file.readlines()
# 将数据逐行插入到mysql中的数据表中
for line in data:
sql = "INSERT INTO table_name (column_name) VALUES ('%s')" % line.strip()
cursor.execute(sql)
# 提交事务并关闭连接
conn.commit()
cursor.close()
conn.close()
```
其中,您需要将localhost、port、user、password、database_name、table_name、column_name按照您自己的MySQL数据库配置进行修改,file.txt则需要替换成您自己的本地文本文件名。
相关问题
python将本地txt文档存入mysql数据库
对于这个问题,我可以回答。您可以使用Python中的MySQL Connector库来实现将本地txt文档存入MySQL数据库的功能。具体方法是读取txt文件的内容,将其存储到一个字符串变量中,然后使用SQL INSERT语句将该字符串插入到MySQL数据库表中。您还需要确保在运行脚本之前已经在MySQL数据库中创建了相应的表,包括需要存储的各列。
python将文件夹中所有txt文档存入mysql数据库举例
好的,这个问题可以回答。
首先需要安装Python的MySQLdb库,然后导入相应的模块:
```python
import os
import MySQLdb
```
接下来连接到MySQL数据库:
```python
db = MySQLdb.connect(host='localhost',
user='root',
passwd='mypassword',
db='mydatabase')
```
然后使用游标进行操作:
```python
cur = db.cursor()
```
使用os模块获取所有txt文档:
```python
file_list = []
for root, dirs, files in os.walk('/path/to/folder'):
for file in files:
if file.endswith('.txt'):
file_list.append(os.path.join(root, file))
```
遍历每个文件,读取文本内容并插入到MySQL数据库中:
```python
for file in file_list:
with open(file, 'r') as f:
content = f.read()
cur.execute("INSERT INTO mytable (filename, content) VALUES (%s, %s)", (file, content))
db.commit()
```
这样就可以将文件夹中的所有txt文档存入到MySQL数据库中了。