python mysql 测试
1: 创建APP
2: 修改setting 节点 TEMPLATES
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'bbs_db',
'USER':'jzgjxj',
'PASSWORD':'abcd1234',
'HOST':'127.0.0.1',
'PORT':'9527'
}
3:注册 app setting 中 节点 INSTALLED_APPS (注意 这里不用添加项目名,只需要添加app的名称即可)
4:编写 models
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
5:python manage.py sqlall app名称
注意:sqlall 命令并没有在数据库中真正创建数据表,只是把SQL语句段打印出来。运行 syncdb 命令
python manage.py syncdb
6: 表创建成功
添加数据: views 中操作即可
p1 = Publisher(name='Addison-Wesley', address='75 Arlington Street',city='Boston', state_province='MA', country='U.S.A.',website='http://www.apress.com/')
p1.save()
p2 = Publisher(name="O'Reilly", address='10 Fawcett St.',city='Cambridge', state_province='MA', country='U.S.A.',website='http://www.oreilly.com/')
p2.save()
publisher_list = Publisher.objects.all()
数据操作部分:
1:数据过滤
Publisher.objects.filter(country="U.S.A.", state_province="CA") #直接获取符合条件的对象
Publisher.objects.filter(name__contains="press") # 类似模糊查询 LIKE '%press%'; 用法是 __contains
Publisher.objects.get(name="Apress Publishing") # 获取单个对象
Publisher.objects.order_by("name") # 指定排序 逆向的话在 name前 加上 - 符号
Publisher.objects.all()[0] # 只显示第一个
p = Publisher.objects.get(name="Addison-Wesley")
p.delete() # 删除对象
|
|