【发布时间】:2022-01-15 01:06:15
【问题描述】:
我是 python 语言和 sql 请求的初学者。我不知道为什么,但是这段代码不起作用。它说我的要求不好。是因为我的变量类型吗?我尝试了几种解决方案,发现已经有几个与我的问题相关的 subjets。但我没有找到解决方案。
我的类ProviderWindow的代码:
from tkinter import Tk, Label, Button, Entry, StringVar
from GeStock_2 import provider
class ProviderWindow(Tk):
def __init__(self):
super().__init__()
self.title("Provider")
self.widgets_provider()
def widgets_provider(self):
# Input field for the new provider.
name_provider = StringVar()
provider_field = Entry(self, textvariable=name_provider)
provider_field.grid(row=0, column=0)
# Button to add a new provider.
provider_add_button = Button(self, text="New provider")
provider_add_button.grid(row=1, column=0, sticky="nesw")
provider_add_button['command'] = lambda: call_function_insert_provider(name_provider)
def call_function_insert_provider(name_provider):
new_provider = provider.Provider(name_provider)
print(new_provider)
print(str(new_provider))
provider.Provider.insert_new_provider(new_provider)
我的班级提供者的代码:
from GeStock_2 import utils
class Provider(object):
def __init__(self, name):
self.name = name
def insert_new_provider(self):
conn = utils.connection()
my_cursor = conn.cursor()
print(self.name)
print(str(self.name))
my_cursor.execute("INSERT INTO `provider` (`id_prov`, `name_prov`) VALUES (NULL, ('" + str(self.name) + "')")
cursor = my_cursor.fetchall()
conn.commit()
return cursor
“utils”代码:
导入 mysql.connector
def connection():
# function that to connect to database.
conn = mysql.connector.connect(user='root', password='', host='localhost', database='gestock_2')
return conn
你能帮帮我吗?谢谢
【问题讨论】:
-
尝试先构造INSERT SQL字符串并打印出来,然后你可能会看到SQL语句有什么问题。另外最好使用 placeholders 来避免 SQL 注入。