Simple library for database interaction (peewee) in python
Python peewee is a module for interaction with db.
pip install peewee
Connection:
To connect with mysql install mysqlclient
pip install mysqlclient
pip install mysql-connector-python
Simple Example:
DROP TABLE IF EXISTS `images`;
CREATE TABLE `images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cnic` varchar(255) NOT NULL,
`image` text NOT NULL,
`name` varchar(255) NOT NULL,
`dob` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
INSERT INTO `images` (`id`, `cnic`, `image`, `name`, `dob`) VALUES
(1, '3333', '333', '333', '3333');
from peewee import *
db = MySQLDatabase('db_images', user='root', password='',
host='localhost', port=3306)
class Images(Model):
cnic = CharField()
dob = CharField()
image = TextField()
name = CharField()
class Meta:
database = db
table_name = 'images'
data = Images.select().limit(10)
for pet in data:
print(pet.id, pet.cnic)
INSERT DATA
insert_it = Images(cnic='3840190909090', image='cool.png')
insert_it.save()
# bob is now stored in the database & Returns: 1,,, save(), the number of rows modified is returned.
OR
ins = Images.create(cnic='38401', image="love.png") #returns a model instance:
Insert Bult + dictionary
data_source = [
{'cnic': '3840190349863', 'name': 'Rizwan Akhtar'},
{'cnic': '3840190349990', 'name': 'val2-2'},
]
for data_dict in data_source:
Images.create(**data_dict)
SELECT DATA:
data = Images.select().where(Images.cnic == '3333').get()
print(data.cnic)
Select with where
Products.select().where(Products.id == "2")
data contain id but you can access other columns also, OR
data = Images.get(Images.cnic == '3333')
print(data.cnic)
SELECT ORDER BY AND LIMIT
productis = Images.select().where((Images.id== 2) & (Images.status == '')).order_by(Images.size.desc(), Images.id.asc()).limit(10)
Multiple conditions
query = Links.select().where((Links.link.contains("loveislife/")) & (Links.status == ""))
lOOP selection
query = Images.select()
for data in query:
print(data.id, data.cnic)
Update data
query = Images.update(name="Rizi Gondal").where(Images.cnic == '3840190349863')
query.execute() # Returns the number of rows that were updated.
Delete Record
query = Images.delete().where(Images.cnic == '3840190349863')
query.execute() # Returns the number of rows deleted.
Close DB
db.close()
Create Models if you have already database
python -m pwiz -e mysql -u root db_images #print all models
python -m pwiz -e mysql -u root db_images > mymodels.py #save models to file
Now we can use these models as
from mymodels import Blog, Entry, Tag, Whatever
print([blog.name for blog in Blog.select()])
http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#pwiz