Python SQLAlchemy

SQLAlchemy是一个Python的ORM工具,所谓ORM就是将关系数据库映射到对象上,减少开发过程中的数据库操作的问题。安装的命令如下:

pip installSQLAlchemy

Python SQLAlchemy_第1张图片

在这里只是简单的测试一下SQLAlchemy,因为Python中内嵌了sqlite3,所以在Python中使用sqlite3我们不需要做任何安装,因此使用sqlite3进行测试。

第一步,导入SQLAlchemy,并初始化DBSession:

#导入:

from sqlalchemy importColumn, String, create_engine

from sqlalchemy.orm importsessionmaker

from sqlalchemy.ext.declarativeimport declarative_base

#创建对象的基类:

Base = declarative_base()

#定义User对象:

class User(Base):

#表的名字:

__tablename__ = 'user'

#表的结构:

id = Column(String(20), primary_key=True)

name = Column(String(20))

#初始化数据库连接:

engine = create_engine('mysql+mysqlconnector://root:password@localhost:3306/test')

#创建DBSession类型:

DBSession =sessionmaker(bind=engine)

#创建session对象:

session = DBSession()

#创建新User对象:

new_user = User(id='5', name='Bob')

#添加到session:

session.add(new_user)

#提交即保存到数据库:

session.commit()

#关闭session:

session.close()

主流数据库的连接方式:

数据库

连接字符串

Microsoft SQLServer

‘mssql+pymssql://username:password@ip:port/dbname’

MySQL

‘mysql://username:password@ip:port/dbname’

oracle

‘orcle://username:password@ip:port/dbname’

PostgreSQL

‘postgresql://username:password@ip:port/dbname’

SQLite

‘sqlite://file_pathname’

参考资料:http://blog.csdn.net/will130/article/details/48502053

你可能感兴趣的:(Python SQLAlchemy)