first_db.py
from kivy.lang import Builder
from kivymd.app import MDApp
import sqlite3
class MainApp(MDApp):
def build(self):
self.theme_cls.theme_style = "Dark"
self.theme_cls.primary_palette = "BlueGray"
# Create Database or connect to one
conn = sqlite3.connect('first_db.db')
# Create a cursor
c = conn.cursor()
# Create a table
c.execute("""CREATE TABLE if not exists customers(
name text)
""")
# Commit changes
conn.commit()
# Close connection
conn.close()
return Builder.load_file('first_db.kv')
def submit(self):
conn = sqlite3.connect('first_db.db')
c = conn.cursor()
# Add a record
c.execute("INSERT INTO customers VALUES (:first)",
{
'first': self.root.ids.word_input.text,
})
# Add a message
self.root.ids.word_label.text = f'{self.root.ids.word_input.text} Added'
# Clear input box
self.root.ids.word_input.text = ''
conn.commit()
conn.close()
def show_records(self):
conn = sqlite3.connect('first_db.db')
c = conn.cursor()
# Grab records from database
c.execute("SELECT * FROM customers")
records = c.fetchall()
word = ''
# Loop thru records
for record in records:
word = f'{word}\n{record[0]}'
self.root.ids.word_label.text = f'{word}'
conn.commit()
conn.close()
MainApp().run()
first_db.kv
MDFloatLayout:
BoxLayout:
orientation: "vertical"
size: root.width, root.height
Label:
id: word_label
text_size: self.size
halign: "center"
valign: "middle"
text: "Enter Name"
font_size: 32
TextInput:
id: word_input
multiline: False
size_hint: (1, .5)
Button:
size_hint: (1, .5)
font_size: 32
text: "Submit"
on_press: app.submit()
Button:
size_hint: (1, .5)
font_size: 32
text: "Show Records"
on_press: app.show_records()