【发布时间】:2022-01-07 02:59:25
【问题描述】:
我通过读取一个 excel 文件并将其写入数据库来编写一个函数。这行得通!
从数据库中获取数据也可以。
我卡住的地方是函数应该读取每一行,计算它并将结果写回数据库。
我还想知道在数据库中写入了多少行,然后将该数字传递给 for 循环。
第一个函数用于读取Excel数据并将其写入数据库:
def Load_into_database():
file_path = label_file["text"]
try:
excel_filename = r"{}".format(file_path)
if excel_filename[-4:] == ".csv":
df = pd.read_csv(excel_filename, header=0, names=['Probe_Dehnung', 'Probe_Standardkraft'], sheet_name='Probe 1', skiprows=2, usecols="A:B")
else:
df = pd.read_excel(excel_filename, header=0, names=['Probe_Dehnung', 'Probe_Standardkraft'], sheet_name='Probe 1', skiprows=2, usecols="A:B")
except ValueError:
tk.messagebox.showerror("Information", "The file you have chosen is invalid")
return None
except FileNotFoundError:
tk.messagebox.showerror("Information", f"No such file as {file_path}")
return None
engine = create_engine("mariadb+mariadbconnector://root:pw123@127.0.0.1:3306/polymer")
df.to_sql('zugversuch_probe_1',
con=engine,
if_exists='append',
index=False)
c.execute("SELECT * FROM zugversuch_probe_1")
records = c.fetchall()
print("Records", records)
calculation(records)
第二个函数是从一列中读取每一行,逐行计算,然后写回数据库:
def calculation(records):
# query the database
for record_id in records:
c.execute("SELECT * FROM zugversuch_probe_1 WHERE ID = " + str(record_id))
records = c.fetchall()[0]
# Berechnung Dehnung
dehnung = calc_dehnung(records[1])
print("Dehnung", dehnung)
sql_command = """
INSERT INTO zugversuch_probe_1
(Dehnung)
VALUES(%s)"""
c.execute("""UPDATE zugversuch_probe_1 SET
Dehnung = %s
WHERE ID = %s""",
(
dehnung.get(),
record_id
))
values = (dehnung.get())
# commit changes
conn.commit
# close connection
conn.close()
def calc_dehnung(value_list):
return (value_list[0] / 0.123) * 100
运行代码后,我收到错误消息:
c.execute("SELECT * FROM zugversuch_probe_1 WHERE ID = " + str(record_id)) mariadb.OperationalError:“where 子句”中的未知列“None”
很遗憾,我也有删除数据后数据库中的ID没有从0重新开始,而是继续计数的问题。
这是数据库的截图: Screenshot Database
这是 Excel 文件的屏幕截图: Screenshot Excel
提前谢谢你
【问题讨论】:
-
你的sql语句容易受到SQL注入owasp.org/www-community/attacks/SQL_Injection
-
是的,但这不是他的问题。此外,只有在处理用户输入时,sql 注入才有意义。我在这里看不到任何用户输入,这似乎是一个离线脚本。可以提一下,但这不是导致他错误的原因。
标签: python sql database mariadb