2016-08-05 36 views
2

我有一個Kivy代碼,其中輸出爲:檢索的MySQL與Kivy

enter image description here

我想更換Box No.與從MySQL返回的字符串

到目前爲止,我已經嘗試實現MySQL到python腳本:

class RemoveScreen(MyLayout): 


    def __init__(self,**kwargs): 
     db = MySQLdb.connect("localhost", "root", "[PASSWORD]", "tcs_microrage_crm") 
     cursor=db.cursor() 
     self.var = StringVar() 
     self.label1 = Label(self, text=0, textvariable=self.var) 
     myvar=str(self.var) 
     #http://stackoverflow.com/questions/775296/python-mysql-parameterized-queries 
     cursor.execute("SELECT part_name FROM stock_lists WHERE part_number = %s", (myvar)) 
     self.myvar=StringVar() 
     self.myvar.set(cursor.fetchone()) 
     self.label2 = Label(self, text=0, textvariable=myvar) 

但是這並沒有奏效。

問:如何執行MySQL查詢並打印kv文件中的單個字符串。

回答

1

爲了向您展示如何做到這一點,我做了一個小例子。
這將搜索數據庫中的水果名稱,並將其名稱和價格輸出到表格中。

from kivy.app import App 

import MySQLdb 

from kivy.uix.boxlayout import BoxLayout 
from kivy.uix.gridlayout import GridLayout 
from kivy.uix.label import Label 
from kivy.uix.button import Button 
from kivy.uix.textinput import TextInput 


class DbCon: 

    def __init__(self): 
     self.db = MySQLdb.connect(user="root",passwd="pw",db="kivy") 
     self.c = self.db.cursor() 

    def get_rows(self,search = ""): 
     self.c.execute("SELECT * FROM fruit WHERE name REGEXP '.*%s.*' LIMIT 3" % search) 
     return self.c.fetchall() 


class Table(BoxLayout): 

    def __init__(self,**kwargs): 
     super(Table,self).__init__(**kwargs) 

     self.orientation = "vertical" 

     self.search_field = BoxLayout(orientation="horizontal") 

     self.search_input = TextInput(text='search',multiline=False) 
     self.search_button = Button(text="search",on_press=self.search) 

     self.search_field.add_widget(self.search_input) 
     self.search_field.add_widget(self.search_button) 

     self.add_widget(self.search_field) 

     self.add_widget(Label(text="table")) 

     self.table = GridLayout(cols=2,rows=4) 
     self.table.add_widget(Label(text="Fruit")) 
     self.table.add_widget(Label(text="Price")) 

     self.rows = [[Label(text="item"),Label(text="price")], 
        [Label(text="item"),Label(text="price")], 
        [Label(text="item"),Label(text="price")]] 

     for item,price in self.rows: 
      self.table.add_widget(item) 
      self.table.add_widget(price) 

     self.add_widget(self.table) 


     self.db = DbCon() 
     self.update_table() 


    def update_table(self,search=""): 
     for index,row in enumerate(self.db.get_rows(search)): 
      self.rows[index][0].text = row[1] 
      self.rows[index][1].text = str(row[2]) 

    def clear_table(self): 
     for index in range(3): 
      self.rows[index][0].text = "" 
      self.rows[index][1].text = "" 


    def search(self, *args): 
     self.clear_table() 
     self.update_table(self.search_input.text) 


class MyApp(App): 
    def build(self): 
     return Table() 


MyApp().run()