方法1
database = PostgresqlDatabase('amos',
**{'host': '192.168.101.214', 'password': 'postgres',
'port': 5432, 'user': 'postgres'})
方法2
database = PostgresqlDatabase(None)
database.init(
database='postgres',
host='192.168.101.214',
user='postgres',
password='postgres'
)
创建新表(模型)
class BaseModel(Model):
class Meta.:
database = database
class StudentsInfo(BaseModel):
student_name = CharField(null=True) # 不同的字段类型大家可以自行谷歌
student_no = IntegerField(primary_key=True)
class Meta.:
db_table = 'student_info'
class StudentsScore(BaseModel):
score = IntegerField(null=False)
student_no = IntegerField(primary_key=True)
subject = CharField(null=False)
class Meta.:
db_table = 'students_score'
database.create_tables([StudentsInfo, StudentsScore]) #有其他的model往列表加即可
从实例化数据库到创建新表完整代码:
# coding:utf-8
from peewee import *
# database = PostgresqlDatabase('amos',
# **{'host': '192.168.101.214', 'password': 'postgres',
# 'port': 5432, 'user': 'postgres'})
database = PostgresqlDatabase(None)
database.init(
database='postgres',
host='192.168.101.214',
user='postgres',
password='postgres'
)
database.connect()
class BaseModel(Model):
class Meta.:
database = database
class StudentsInfo(BaseModel):
student_name = CharField(null=False)
student_no = IntegerField(primary_key=True)
class Meta.:
db_table = 'students_info' # 这个就是数据库的表名
class StudentsScore(BaseModel):
score = IntegerField(null=False)
student_no = IntegerField(primary_key=True)
subject = CharField(null=False)
class Meta.:
db_table = 'students_score' # 这个就是数据库的表名
database.create_tables([StudentsInfo, StudentsScore]) #有其他的model往列表加即可
database.close()
根据已有的表自动生成模型
如果不需要自己去创建表,已有现成的表可用,可以使用下面的命令生成模型
python -m pwiz -e postgresql -H 192.168.23.127 -p5432 -uroot -P dbname >db.py
解释:-e数据库类型 比如mysql、postgresql
-H数据库ip
-p端口
-u数据库用户名
-P密码
dbname为db名
db.py自动生成的py文件名
纯手打,多谢支持。