如何用python将本地txt文件存入mysql
时间: 2024-05-20 09:19:31 浏览: 9
数据库中?
可以使用Python中的MySQL Connector模块:
1. 首先,需要安装MySQL Connector模块,可以通过pip install mysql-connector-python 命令来安装
2. 连接MySQL数据库,可以使用以下代码:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="databasename"
)
3. 创建表格和列,可以使用以下代码:
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE tablename (id INT AUTO_INCREMENT PRIMARY KEY, textcontent TEXT)")
4. 将本地txt文件读取并插入MySQL数据库中:
with open("filename.txt", "r") as file:
textcontent = file.read()
sql = "INSERT INTO tablename (textcontent) VALUES (%s)"
val = (textcontent, )
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
以上是一般的示例,你需要改变一些参数来适应你自己的情况,比如连接MySQL时的主机名、用户名、密码、数据库名称等等。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)