Sqlalchemy 简明教程

SQLAlchemy Core - Connecting to Database

在上一章中,我们讨论了 SQLAlchemy 中的表达式语言。现在,让我们继续执行连接到数据库的步骤。

In the previous chapter, we have discussed about expression Language in SQLAlchemy. Now let us proceed towards the steps involved in connecting to a database.

引擎类连接一个 Pool and Dialect together 来提供数据库 connectivity and behavior 的源。使用 create_engine() 函数对引擎类的一个对象进行实例化。

Engine class connects a Pool and Dialect together to provide a source of database connectivity and behavior. An object of Engine class is instantiated using the create_engine() function.

create_engine() 函数将数据库作为单个参数。数据库不需要在任何地方进行定义。标准调用形式必须将 URL 作为第一个位置参数进行发送,它通常是一个表示数据库方言和连接参数的字符串。使用下面提供的代码,我们可以创建一个数据库。

The create_engine() function takes the database as one argument. The database is not needed to be defined anywhere. The standard calling form has to send the URL as the first positional argument, usually a string that indicates database dialect and connection arguments. Using the code given below, we can create a database.

>>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite:///college.db', echo = True)

对于 MySQL database ,使用以下命令−

For a MySQL database, use the below command −

engine = create_engine("mysql://user:pwd@localhost/college",echo = True)

为了具体指定要用于连接的 DB-APIURL string 需要采用以下形式−

To specifically mention DB-API to be used for connection, the URL string takes the form as follows −

dialect[+driver]://user:password@host/dbname

例如,如果你正在使用 PyMySQL driver with MySQL ,使用以下命令 −

For example, if you are using PyMySQL driver with MySQL, use the following command −

mysql+pymysql://<username>:<password>@<host>/<dbname>

echo flag 是设置 SQLAlchemy 日志记录的一个快捷方式,它是通过 Python 的标准日志记录模块来完成的。在后续章节中,我们将学习所有生成的 SQL。若要隐藏冗余输出,请将 echo 属性设置为 None 。create_engine() 函数的其他参数可能是方言专有的。

The echo flag is a shortcut to set up SQLAlchemy logging, which is accomplished via Python’s standard logging module. In the subsequent chapters, we will learn all the generated SQLs. To hide the verbose output, set echo attribute to None. Other arguments to create_engine() function may be dialect specific.

create_engine() 函数返回一个 Engine object 。引擎类的某些重要方法是 −

The create_engine() function returns an Engine object. Some important methods of Engine class are −

Sr.No.

Method & Description

1

connect() Returns connection object

2

execute() Executes a SQL statement construct

3

begin() Returns a context manager delivering a Connection with a Transaction established. Upon successful operation, the Transaction is committed, else it is rolled back

4

dispose() Disposes of the connection pool used by the Engine

5

driver() Driver name of the Dialect in use by the Engine

6

table_names() Returns a list of all table names available in the database

7

transaction() Executes the given function within a transaction boundary