1、当用python开发项目的时候,我们发现经常需要用到数据库来存储数据,所以,连接数据库,并能够灵活的处理数据库特别的重要,下面有两种用代码来操作数据库的方法,一种是通过传统的方法;另外一种则是通过ORM--Peewee的方法来处理数据库;
2、下面第一个操作数据库的方法可能有点笨,就是通过实际数据库的语句来实现对数据库表结构的操作:
import mysql.connector
db=mysql.connector.connect(user="root",password="123456",database="peewee")###连接数据库peewee,登陆账户为root,密码为123456;
db.create_tables([Person,Relationship,Message]) #### 创建三个表格:Person/Relationship/Message;
# cursor=db.cursor() ###使用cursor()方法获取操作游标
# cursor.execute("select person_no from Person") ##使用execute方法执行SQL语句
# db=cursor.fetchone() ##使用fetchone()方法获取一条数据
提示:如果以上运行时出现报错:No module name mysql.connector,说明大家是没有安装这个mysql.connector这个模块,pip install mysql-connector-python就可以了。
3、接下来给大家介绍的用peewee来操作数据库表格的方法:
from peewee import *
db = MySQLDatabase(
database = 'test',#string
passwd = 'test', #string
user = 'test', #string
host = 'localhost', #string
port = 3306, # int, 可不写
)
# 创建数据库的代理
db_proxy = Proxy()
# 使用代理数据库创建表
class BaseModel(Model):
class Meta:
database = db_proxy
class User(BaseModel):
username = CharField()
# 根据配置条件来选择不同的数据库
if app.config['DEBUG']:
db= SqliteDatabase('local.db')
elif app.config['TESTING']:
db= SqliteDatabase(':memory:')
else:
db= PostgresqlDatabase('mega_production_db')
# 通过代理来根据配置条件将选取的数据库初始化
database_proxy.initialize(db)
友情链接: