1. 程式人生 > >python學習之PyMySql 1 db的方法

python學習之PyMySql 1 db的方法

我們通過程式碼查看了方法。

DataError
DatabaseError
Error
IntegrityError
InterfaceError
InternalError
NotSupportedError
OperationalError
ProgrammingError
Warning
affected_rows
autocommit
autocommit_mode
begin
bind_address
character_set_name
charset
client_flag
close
commit
connect
connect_timeout
cursor
cursorclass
db
decoders
encoders
encoding
escape
escape_string
get_autocommit
get_host_info
get_proto_info
get_server_info
host
host_info
init_command
insert_id
kill
literal
max_allowed_packet
next_result
open
password
ping
port
protocol_version
query
rollback
salt
select_db
server_capabilities
server_charset
server_language
server_status
server_thread_id
server_version
set_charset
show_warnings
sql_mode
ssl
thread_id
unix_socket
use_unicode
user
write_packet

close函式

    def close(self):
        """
        Send the quit message and close the socket.

        See `Connection.close() <https://www.python.org/dev/peps/pep-0249/#Connection.close>`_
        in the specification.
        
        :raise Error: If the connection is already closed.
        """

翻譯:傳送退出資訊並且關閉套接字。如果連線已經關閉就會丟擲異常。多次關閉或者異常關閉了。

open函式

@property
    def open(self):
        """Return True if the connection is open"""
        return self._sock is not None

翻譯:如果連線是開啟狀態就會返回Ture,反之亦然。

begin函式

def begin(self):
        """Begin transaction."""

翻譯:無返回值,開啟事務。

commit函式

def commit(self):
        """
        Commit changes to stable storage.
        
        See `Connection.commit() <https://www.python.org/dev/peps/pep-0249/#commit>`_
        in the specification.
        """

翻譯:將變化後的資料儲存到記憶體中,幫助文件

rollback函式

def rollback(self):
        """
        Roll back the current transaction.
        
        See `Connection.rollback() <https://www.python.org/dev/peps/pep-0249/#rollback>`_
        in the specification.
        """

show_warnings函式

 def show_warnings(self):
        """Send the "SHOW WARNINGS" SQL command."""
        self._execute_command(COMMAND.COM_QUERY, "SHOW WARNINGS")
        result = MySQLResult(self)
        result.read()
        return result.rows

翻譯:傳送show_warnings指令,將得到的結果返回回來。

literal函式

    def literal(self, obj):
        """Alias for escape()
        
        Non-standard, for internal use; do not use this in your applications.
        """
        return self.escape(obj, self.encoders)

翻譯:escape的別名

cursor函式

def cursor(self, cursor=None):
        """
        Create a new cursor to execute queries with.
        
        :param cursor: The type of cursor to create; one of :py:class:`Cursor`,
            :py:class:`SSCursor`, :py:class:`DictCursor`, or :py:class:`SSDictCursor`.
            None means use Cursor.
        """
        if cursor:
            return cursor(self)
        return self.cursorclass(self)

翻譯:為查詢結果建立一個遊標,引數cursor:表示將要遊標建立的型別。有如下幾種Cursor預設。

SSCursor,DictCursor,或者SSDictCursor.這些都在pymysql.cursor裡面有定義。

query函式

# The following methods are INTERNAL USE ONLY (called from Cursor)
    def query(self, sql, unbuffered=False):
        # if DEBUG:
        #     print("DEBUG: sending query:", sql)
        if isinstance(sql, text_type) and not (JYTHON or IRONPYTHON):
            if PY2:
                sql = sql.encode(self.encoding)
            else:
                sql = sql.encode(self.encoding, 'surrogateescape')
        self._execute_command(COMMAND.COM_QUERY, sql)
        self._affected_rows = self._read_query_result(unbuffered=unbuffered)
        return self._affected_rows

翻譯:這個方法是用來做查詢的,返回的結果是影響的行數。

try:
    db = pymysql.connect(host="127.0.0.1",user="root",port=3306,password="123456",database="android")
    print(type(db.query("show tables")))
    db.close()
    print("連線成功")
except:
    print("連線失敗")
<class 'int'>
連線成功

next_result函式

def next_result(self, unbuffered=False):
        self._affected_rows = self._read_query_result(unbuffered=unbuffered)
        return self._affected_rows

翻譯:獲取查詢結果,返回是行數。

affected_rows函式

def affected_rows(self):
        return self._affected_rows

翻譯:返回影響的行數。

ping函式

def ping(self, reconnect=True):
        """
        Check if the server is alive.
        
        :param reconnect: If the connection is closed, reconnect.
        :raise Error: If the connection is closed and reconnect=False.
        """
        if self._sock is None:
            if reconnect:
                self.connect()
                reconnect = False
            else:
                raise err.Error("Already closed")
        try:
            self._execute_command(COMMAND.COM_PING, "")
            self._read_ok_packet()
        except Exception:
            if reconnect:
                self.connect()
                self.ping(False)
            else:
                raise

翻譯:檢測主機是否存活,預設重新連線。如果當前的sock為None且非重連模式,則會丟擲異常。然後進行查詢。

cursor函式

def cursor(self, cursor=None):
        """
        Create a new cursor to execute queries with.
        
        :param cursor: The type of cursor to create; one of :py:class:`Cursor`,
            :py:class:`SSCursor`, :py:class:`DictCursor`, or :py:class:`SSDictCursor`.
            None means use Cursor.
        """
        if cursor:
            return cursor(self)
        return self.cursorclass(self)

翻譯:

set_charset函式

def set_charset(self, charset):
        # Make sure charset is supported.
        encoding = charset_by_name(charset).encoding


        self._execute_command(COMMAND.COM_QUERY, "SET NAMES %s" % self.escape(charset))
        self._read_packet()
        self.charset = charset
        self.encoding = encoding

翻譯:首先確保支援charset,設定字符集。設定解碼格式。