English 中文(简体)
Peewee - Using MySQL
  • 时间:2024-09-17

Peewee - Using MySQL


Previous Page Next Page  

As mentioned earper, Peewee supports MySQL database through MySQLDatabase class. However, unpke SQLite database, Peewee can’t create a MySql database. You need to create it manually or using functionapty of DB-API comppant module such as pymysql.

First, you should have MySQL server installed in your machine. It can be a standalone MySQL server installed from https://dev.mysql.com/downloads/installer/.

You can also work on Apache bundled with MySQL (such as XAMPP downloaded and installed from https://www.apachefriends.org/download.html ).

Next, we install pymysql module, DB-API compatible Python driver.


pip install pymysql

The create a new database named mydatabase. We shall use phpmyadmin interface available in XAMPP.

My Databases

If you choose to create database programmatically, use following Python script −


import pymysql

conn = pymysql.connect(host= localhost , user= root , password=  )
conn.cursor().execute( CREATE DATABASE mydatabase )
conn.close()

Once a database is created on the server, we can now declare a model and thereby, create a mapped table in it.

The MySQLDatabase object requires server credentials such as host, port, user name and password.


from peewee import *
db = MySQLDatabase( mydatabase , host= localhost , port=3306, user= root , password=  )
class MyUser (Model):
   name=TextField()
   city=TextField(constraints=[SQL("DEFAULT  Mumbai ")])
   age=IntegerField()
   class Meta:
      database=db
      db_table= MyUser 
db.connect()
db.create_tables([MyUser])

The Phpmyadmin web interface now shows myuser table created.

Php My Admin Advertisements