python学习之PyMySql 2 cursor的方法

Mysql官方文档 https://dev.mysql.com/doc/connector-python/en/connector-python-introduction.html

Cursor

"""
    This is the object you use to interact with the database.

    Do not create an instance of a Cursor yourself. Call
    connections.Connection.cursor().

    See `Cursor <https://www.python.org/dev/peps/pep-0249/#cursor-objects>`_ in
    the specification.
    """

    #: Max statement size which :meth:`executemany` generates.
    #:
    #: Max size of allowed statement is max_allowed_packet - packet_header_size.
    #: Default value of max_allowed_packet is 1048576.

翻译:这个类是用来操作数据库的类。不要创建自己的Cursor实力,这个类在connections.Connection.cursor().

Curosr帮助文档

.close()

Close the connection now (rather than whenever .__del__() is called).

The connection will be unusable from this point forward; an Error (or subclass) exception will be raised if any operation is attempted with the connection. The same applies to all cursor objects trying to use the connection. Note that closing a connection without committing the changes first will cause an implicit rollback to be performed.

翻译:立刻关闭连接,而不是在系统析构该实例的时候。连接从这之后就不能再被使用。如果对这个对象进行任何其他操作,将会抛出对应的异常。这些适用于所有的Cursor类型。如果在关闭连接之前没有提交这些变化将会对之前的事务进行回滚。

.commit()

Commit any pending transaction to the database.

Note that if the database supports an auto-commit feature, this must be initially off. An interface method may be provided to turn it back on.

Database modules that do not support transactions should implement this method with void functionality.

翻译:提交所有的将要执行的操作到数据库。如果数据库支持自动提交,那么这个最初就应该是关闭状态。一个借口方法可能会重启。数据库模块如果不支持事务,那么就应该事先这个方法并且这个方法不能进行任何操作。

.rollback()

This method is optional since not all databases provide transaction support. [3]

In case a database does provide transactions this method causes the database to roll back to the start of any pending transaction. Closing a connection without committing the changes first will cause an implicit rollback to be performed.

翻译:因为不是所有的数据库都支持事务,所以这个方法是可选择的。如果数据库不支持事务,那么这个方法将会捯饬回滚到最初的状态。如果在关闭连接的时候没有提交这些事务变化,那么就会导致隐形的回滚操作。也就是之前的所有操作将不会被存入数据库。

Cursor methods

.callprocprocname [,  parameters ] )

(This method is optional since not all databases provide stored procedures. [3])

Call a stored database procedure with the given name. The sequence of parameters must contain one entry for each argument that the procedure expects. The result of the call is returned as modified copy of the input sequence. Input parameters are left untouched, output and input/output parameters replaced with possibly new values.

The procedure may also provide a result set as output. This must then be made available through the standard .fetch*()methods.

翻译:因为不是所有的数据库都支持存储程序,所以这个方法是可供选择的。调用一个存储程序名字 porcname,参数列表里面放的是这个程序需要的参数集合,返回的结果是经过格式化后的输入列表。懒得翻译了。。。

.close()

Close the cursor now (rather than whenever __del__ is called).

The cursor will be unusable from this point forward; an Error (or subclass) exception will be raised if any operation is attempted with the cursor.

.execute( operation [,  parameters])

Prepare and execute a database operation (query or command).

Parameters may be provided as sequence or mapping and will be bound to variables in the operation. Variables are specified in a database-specific notation (see the module's paramstyle attribute for details). [5]

A reference to the operation will be retained by the cursor. If the same operation object is passed in again, then the cursor can optimize its behavior. This is most effective for algorithms where the same operation is used, but different parameters are bound to it (many times).

For maximum efficiency when reusing an operation, it is best to use the .setinputsizes() method to specify the parameter types and sizes ahead of time. It is legal for a parameter to not match the predefined information; the implementation should compensate, possibly with a loss of efficiency.

The parameters may also be specified as list of tuples to e.g. insert multiple rows in a single operation, but this kind of usage is deprecated: .executemany() should be used instead.

Return values are not defined.

预处理并执行数据库操作,查询或者指令。
参数列表是以序列或者图的形式进行存储,并且这些参数都会绑定到对应的SQL中(参数operation)。相关操作将会被cursor保留。如果同样的操作被在此传入,那么cursor可以完善他的行为。这种算法是对同样操作最有效的利用。然后不同的参数进行绑定填充。
为了最大化的复用一个操作,最好是通过setinputsizes方法来提前指明types和times。如果传入的参数和之前定义的信息不符这也是合法的。

这些参数可能被放入集合tuple中。比如在同一个操作插入多行,但是这种行为是不推荐的,可以使用executemany() 。

返回值未定义。

这是官方文档上面可以进行占位的。

paramstyle Meaning
qmark Question mark style, e.g. ...WHERE name=?
numeric Numeric, positional style, e.g. ...WHERE name=:1
named Named style, e.g. ...WHERE name=:name
format ANSI C printf format codes, e.g. ...WHERE name=%s
pyformat Python extended format codes, e.g. ...WHERE name=%(name)s
一般都是使用最后两种,前面的好多都不支持了。


.executemanyoperationseq_of_parameters )

Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters.

Modules are free to implement this method using multiple calls to the .execute() method or by using array operations to have the database process the sequence as a whole in one call.

Use of this method for an operation which produces one or more result sets constitutes undefined behavior, and the implementation is permitted (but not required) to raise an exception when it detects that a result set has been created by an invocation of the operation.

The same comments as for .execute() also apply accordingly to this method.

Return values are not defined.

翻译:预处理指令并执行指令。

.fetchone()

Fetch the next row of a query result set, returning a single sequence, or None when no more data is available. [6]

An Error (or subclass) exception is raised if the previous call to .execute*() did not produce any result set or no call was issued yet.

翻译:获取下一行的查询结果集,返回一行数据,如果没有更多的数据则返回None
如果之前执行的execute没有返回任何的结果将会抛出异常。或者之前并没有进行调用execute方法

.fetchmany([ size=cursor.arraysize])

Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a list of tuples). An empty sequence is returned when no more rows are available.

The number of rows to fetch per call is specified by the parameter. If it is not given, the cursor's arraysize determines the number of rows to be fetched. The method should try to fetch as many rows as indicated by the size parameter. If this is not possible due to the specified number of rows not being available, fewer rows may be returned.

An Error (or subclass) exception is raised if the previous call to .execute*() did not produce any result set or no call was issued yet.

Note there are performance considerations involved with the size parameter. For optimal performance, it is usually best to use the .arraysize attribute. If the size parameter is used, then it is best for it to retain the same value from one .fetchmany() call to the next.

翻译:获取一定数目的查询结果集,返回一个结合,一个集合,集合的元素是元组。如果没有剩余的结果则返回空元组。
每一次获取的行数由参数size指明,如果没有给出参数,默认获取所有。这个方法会尽力的去获取由参数指定数目的结果。如果指定的数目大于剩余结果的数目,那么放回的实际数目是剩余结果的数目。
如果之前没有调用或者execute执行后没有返回结果集,那么将会抛出异常。
在这里我们考虑到size参数被指明,但是为了最佳的操作,最好是使用arraysize,如果size被指明,后面所有的参数最好是保持同样的大小。

.fetchall()

Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples). Note that the cursor's arraysize attribute can affect the performance of this operation.

An Error (or subclass) exception is raised if the previous call to .execute*() did not produce any result set or no call was issued yet.

翻译:获取所有的查询结果集。返回的结果是一个list集合,集合的每一个元素是一个元组。cursor的arraysize属性将会影响这个操作。
如果之前没有调用execute或者是没有返回结果集,那么将会抛出异常。

.nextset()

(This method is optional since not all databases support multiple result sets. [3])

This method will make the cursor skip to the next available set, discarding any remaining rows from the current set.

If there are no more sets, the method returns None. Otherwise, it returns a true value and subsequent calls to the .fetch*()methods will return rows from the next result set.

An Error (or subclass) exception is raised if the previous call to .execute*() did not produce any result set or no call was issued yet.

翻译:

.arraysize

This read/write attribute specifies the number of rows to fetch at a time with .fetchmany(). It defaults to 1 meaning to fetch a single row at a time.

Implementations must observe this value with respect to the .fetchmany() method, but are free to interact with the database a single row at a time. It may also be used in the implementation of .executemany().

.setinputsizes( sizes)

This can be used before a call to .execute*() to predefine memory areas for the operation's parameters.

sizes is specified as a sequence — one item for each input parameter. The item should be a Type Object that corresponds to the input that will be used, or it should be an integer specifying the maximum length of a string parameter. If the item isNone, then no predefined memory area will be reserved for that column (this is useful to avoid predefined areas for large inputs).

This method would be used before the .execute*() method is invoked.

Implementations are free to have this method do nothing and users are free to not use it.

翻译:在执行execute操作之前设定,用于指明操作的operation的参数个数。
参数sizes是一个集合,每一次传入参数的数目。item是类型必须是对应传入项的类型。也可以是int类型的来指明一个字符串类型的数据的最大长度。

.setoutputsize( size [,  column])

Set a column buffer size for fetches of large columns (e.g. LONGs, BLOBs, etc.). The column is specified as an index into the result sequence. Not specifying the column will set the default size for all large columns in the cursor.

This method would be used before the .execute*() method is invoked.

Implementations are free to have this method do nothing and users are free to not use it.

mogrify 方法

def mogrify(self, query, args=None):
        """
        Returns the exact string that is sent to the database by calling the
        execute() method.

        This method follows the extension to the DB API 2.0 followed by Psycopg.
        """
        conn = self._get_db()
        if PY2:  # Use bytes on Python 2 always
            query = self._ensure_bytes(query, encoding=conn.encoding)

        if args is not None:
            query = query % self._escape_args(args, conn)

        return query
翻译:返回execute方法将要实际执行的sql语句。这个可以用来查看自己的sql语句的格式以及错误发生在什么地方。



猜你喜欢

转载自blog.csdn.net/rubikchen/article/details/80520679