Thursday, September 29, 2016

Python Connect Database Using peewee


First install peewee using pip

pip3 install peewee
Now we have to install MySQLdb or PyMySQL

To install PyMySQL run following command:
sudo pip3 install PyMySQL
Now our basic Configuration done.
Lets create a sample program to connect database and retrieve information from an existing table
import peewee
from peewee import *
db = MySQLDatabase('Word', user='root' , passwd='csecu')


class Words(peewee.Model):
    name = peewee.CharField()
    engdes = peewee.CharField()
    pages = peewee.IntegerField()

    class Meta:
        database = db


for words in Words.filter(name="bappu"):
    print(words.pages)
Lets breakdown :

db = MySQLDatabase('Word', user='root' , passwd='csecu')
This line is used to establish a database connection.

class Words(peewee.Model):
    name = peewee.CharField()
    engdes = peewee.CharField()
    pages = peewee.IntegerField()
Here class Words, represents that, we have a table name words in Word database and it has 3 columns. Which are name, engdes and pages 

class Meta:
        database = db

This means that Words model uses the "Word" database.
for words in Words.filter(name="bappu"):
    print(words.pages)
This is used to select all data where name = bappu and showing number of pages

0 comments:

Post a Comment