我想使用Pandas将数据从Excel导入数据库。
在我使用MariaDB创建的数据库中,第一列中有一个自动递增的ID,第二列中有一个时间戳。我想要从MariaDB中的第三列插入我在Excel中的数据。此外,Excel中的数据没有标题。
我已经写了一些东西,但它不能工作。任何想法都将不胜感激!
这是我的代码,我用它将一个Excel文件插入到我的MariaDB数据库中:
import pandas as pd
from sqlalchemy import create_engine
df = pd.read_excel(r'C:/Users/Zlatan/Desktop/Project_PolymerSQL/guitest.xlsx', header=None, index_col=0)
# format: mysql://user:pass@host/db
engine = create_engine("mariadb+mariadbconnector://root:pass@127.0.0.1:3306/polymer")
df.to_sql('guitest', con=engine, if_exists='append', index=False)这是Excel中的数据示例(不带标题)。数据从A列和第1行开始:
test11 test21 1
test11 test21 2
test11 test21 3
test11 test21 4
test11 test21 5
test11 test21 6
test11 test21 7
...发布于 2021-09-25 06:24:30
为此,您可以在读取Excel文件时指定列名,然后在写入数据库之前删除不需要的列。要写入数据库的列名必须与数据库表中的列名匹配。
给定此表
+-------+-----------+------+-----+---------------------+-------------------------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-----------+------+-----+---------------------+-------------------------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| ts | timestamp | NO | | current_timestamp() | on update current_timestamp() |
| col_c | int(11) | YES | | NULL | |
+-------+-----------+------+-----+---------------------+-------------------------------+这段代码
df = pd.read_excel('guitest.xlsx', header=None, index_col=0, names=['col_b', 'col_c'])
new_df = df.drop(df.columns[[0]], axis=1)
new_df.to_sql('guitest', con=engine, if_exists='append', index=False)将插入这些行
+----+---------------------+-------+
| id | ts | col_c |
+----+---------------------+-------+
| 1 | 2021-09-25 07:21:08 | 1 |
| 2 | 2021-09-25 07:21:08 | 2 |
| 3 | 2021-09-25 07:21:08 | 3 |
| 4 | 2021-09-25 07:21:08 | 4 |
| 5 | 2021-09-25 07:21:08 | 5 |
| 6 | 2021-09-25 07:21:08 | 6 |
| 7 | 2021-09-25 07:21:08 | 7 |
+----+---------------------+-------+https://stackoverflow.com/questions/69319011
复制相似问题