2016-11-28 107 views
-2

我回來時遇到了一些麻煩._。
有人能幫助我嗎?當我想從Tkinter Entry(Widgets)向我的數據庫添加一些數據時遇到問題。
我在我的數據庫中有「book」表,我想把tkinter的一些數據放到我的表「book」中。
我已經使用get但我沒有得到任何東西在我的程序 有人可以幫助我嗎?從Tkinter Python獲取數據到數據庫MySQL

謝謝。哦,是的,這是我的腳本:)

from tkinter import * 
import mysql.connector as mc 
import tkinter.messagebox as tm 


def put(*args): 
    e_code = i_code.get() 
    e_name = i_name.get() 
    e_price = i_price.get() 
    conn = mc.connect(user="root", password="mypassword", host="localhost", database="book_test") 
    cur = conn.cursor() 
    cur.execute("insert into book(book_code, book_name, book_price) values('"+e_code+"', '"+e_name+"', '"+e_price+"')") 
    conn.close() 



root = Tk() 
root.title("GET DATA") 

mainframe = Frame(root) 
mainframe.pack() 

i_code = IntVar() 
i_name = StringVar() 
i_price = IntVar() 


codeEntry = Entry(mainframe, width=7, textvariable=i_code) 
nameEntry = Entry(mainframe, width=7, textvariable=i_name) 
priceEntry = Entry(mainframe, width=7, textvariable=i_price) 

codeEntry.grid(row=0, column=1) 
nameEntry.grid(row=1, column=1) 
priceEntry.grid(row=2, column=1) 

Label(mainframe, text='Book Code').grid(row=0, column=0) 
Label(mainframe, text='Book Name').grid(row=1, column=0) 
Label(mainframe, text='Book Price').grid(row=2, column=0) 

Button(mainframe, text="Insert", command=put).grid(row=3, column=1) 


root.mainloop() 

我得到這個錯誤,有人可以幫助我嗎?或者給我提供線索hahaha ._。

Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__return self.func(*args)
File "/home/oncom/PycharmProjects/guiProject/fkinggetdata.py", line 13, in put
cur.execute("insert into book(book_code, book_name, book_price) values('"+e_code+"', '"+e_name+"', '"+e_price+"')")
TypeError: Can't convert 'int' object to str implicitly

+0

目前尚不清楚你的問題是什麼。你有錯誤信息嗎? – scotty3785

+0

等待,我會隱藏嘗試和異常..... – Oncom

+0

@ scotty3785老兄你可以查看我編輯的問題以獲取更多信息hehehe -_- 謝謝 – Oncom

回答

3

你在錯誤信息的一切。

您不能連接字符串和數字。你必須數字轉換成字符串str(i_code)str(i_price)您連接

"... values('" + str(e_code) + "', '" + e_name + "', '" + str(e_price) + "')" 

前,但是,你應該在SQL查詢和使用的元組與?值作爲第二個參數

cur.execute("INSERT INTO book(book_code, book_name, book_price) VALUES('?', '?', '?')", (e_code, e_name, e_price)) 

這是首選方法。它可以防止SQL注入。

+0

使用?是做到這一點的正確方法。 PS你有一個錯字VALUSE應該是VALUES。 – scotty3785

+0

@ scotty3785是的,當我改變爲大寫字母,使其更易讀錯字:) – furas

+0

@furas感謝兄弟爲您的答案,但在我的表中,它仍然是空的當我使用str(e_code),但如果我使用值('? ','?','?')我得到錯誤'不是所有的參數都在SQL語句中使用。噢是在我的表中,book_code是int auto_increment,book_name是varchar,書價是int ._。你知道發生了什麼,而我使用+ str(e_code)+沒有任何錯誤,但我的表仍然是空的-_-謝謝;;) – Oncom