mysql官網關於python的API是最經典的學習材料,相信對於所有函數瀏覽一遍以后,Mysql數據庫用起來一定得心應手。
首先看一下Connector/Python API包含哪些類和模塊。
Module mysql.connector Class connection.MySQLConnection Class cursor.MySQLCursor Class cursor.MySQLCursorBuffered Class cursor.MySQLCursorPrepared Class constants.ClientFlag Class constants.FieldType Class constants.SQLMode Class constants.CharacterSet Class constants.RefreshOption Errors and Exceptions
一、mysql.connector模塊
1 Constructor connection.MySQLConnection(**kwargs) 2 Method MySQLConnection.close() 3 Method MySQLConnection.config(**kwargs) 4 Method MySQLConnection.connect(**kwargs) 5 Method MySQLConnection.commit() 6 Method MySQLConnection.cursor(buffered=None, raw=None, cursor_class=None) 7 Method MySQLConnection.cmd_change_user(username='', password='', database='', charset=33) 8 Method MySQLConnection.cmd_debug() 9 Method MySQLConnection.cmd_init_db(database) 10 Method MySQLConnection.cmd_ping() 11 Method MySQLConnection.cmd_process_info() 12 Method MySQLConnection.cmd_process_kill(mysql_pid) 13 Method MySQLConnection.cmd_quit() 14 Method MySQLConnection.cmd_query(statement) 15 Method MySQLConnection.cmd_query_iter(statement) 16 Method MySQLConnection.cmd_refresh(options) 17 Method MySQLConnection.cmd_shutdown() 18 Method MySQLConnection.cmd_statistics() 19 Method MySQLConnection.disconnect() 20 Method MySQLConnection.get_rows(count=None) 21 Method MySQLConnection.get_row() 22 Method MySQLConnection.get_server_info() 23 Method MySQLConnection.get_server_version() 24 Method MySQLConnection.is_connected() 25 Method MySQLConnection.isset_client_flag(flag) 26 Method MySQLConnection.ping(attempts=1, delay=0) 27 Method MySQLConnection.reconnect(attempts=1, delay=0) 28 Method MySQLConnection.rollback() 29 Method MySQLConnection.set_charset_collation(charset=None, collation=None) 30 Method MySQLConnection.set_client_flags(flags) 31 Method MySQLConnection.start_transaction() 32 Property MySQLConnection.autocommit 33 Property MySQLConnection.charset_name 34 Property MySQLConnection.collation_name 35 Property MySQLConnection.connection_id 36 Property MySQLConnection.database 37 Property MySQLConnection.get_warnings 38 Property MySQLConnection.in_transaction 39 Property MySQLConnection.raise_on_warnings 40 Property MySQLConnection.server_host 41 Property MySQLConnection.server_port 42 Property MySQLConnection.sql_mode 43 Property MySQLConnection.time_zone 44 Property MySQLConnection.unix_socket 45 Property MySQLConnection.user
mysql.connector提供頂層的方法和屬性。具體函數如下:
Method mysql.connector.connect()
該方法用來連接MySQL服務器。如果沒有提供任何參數,將使用默認配置。關於函數的參數列表,參見:
建立連接的方法有兩種:
1、使用mysql.connector.connect()方法:
cnx=mysql.connector.connect(user='joe',database='test')
2、使用mysql.connector.MySQLConnection():
cnx = MySQLConnection(user='joe', database='test')
Property mysql.connector.apilevel
這個屬性是用來標示所支持的數據庫API的等級(level)。
>>> mysql.connector.apilevel
'2.0'
Property mysql.connector.paramstyle
標示參數默認的樣式
>>> mysql.connector.paramstyle
'pyformat'
Property mysql.connector.threadsafety
標示支持的線程安全等級
>>> mysql.connector.threadsafety
1
Property mysql.connector.__version__
Connector/Python的版本號
Property mysql.connector.__version_info__
Connector/Python的版本信息
二、類 connection.MySQLConnection
包含以下方法和屬性:
Constructor connection.MySQLConnection(**kwargs)
Method MySQLConnection.close()
相當於類中disconnect()方法
Method MySQLConnection.config(**kwargs)
對一個已經實例化的MySQLConnection對象進行配置。
cnx = mysql.connector.connect(user='joe', database='test')
# Connected as 'joe'
cnx.config(user='jane')
cnx.reconnect()
# Now connected as 'jane'
Method MySQLConnection.connect(**kwargs)
Method MySQLConnection.commit()
在對數據庫進行更改后調用此函數,使得改變立即生效。
>>> cursor.execute("INSERT INTO employees (first_name) VALUES (%s)", ('Jane'))
>>> cnx.commit()
Method MySQLConnection.cursor(buffered=None, raw=None, cursor_class=None)
如果buffered為ture,在cursor中會獲得SQL語句執行后的所有結果,如果raw設置為true,則跳過由MYSQL數據向python數據類型的轉換,自己執行轉換。
返回的對象類型由buffered和raw參數決定:
If not buffered and not raw: cursor.MySQLCursor
If buffered and not raw: cursor.MySQLCursorBuffered
If buffered and raw: cursor.MySQLCursorBufferedRaw
If not buffered and raw: cursor.MySQLCursorRaw
Returns a CursorBase instance.
Method MySQLConnection.cmd_change_user(username='', password='', database='', charset=33)
改變用戶
Method MySQLConnection.cmd_debug()
該方法需要root權限,可以將debug信息寫入error log中。
Method MySQLConnection.cmd_init_db(database)
制定默認的數據庫
Method MySQLConnection.cmd_ping()
Method MySQLConnection.cmd_process_info()
use the SHOW PROCESSLIST statement or query the tables found in the database INFORMATION_SCHEMA.
Method MySQLConnection.cmd_process_kill(mysql_pid)
關閉mysql進程。以下兩種方法有同樣的作用:
>>> cnx.cmd_process_kill(123)
>>> cnx.cmd_query('KILL 123')
Method MySQLConnection.cmd_quit()
關閉連接
Method MySQLConnection.cmd_query(statement)
發送statement語句到MYSQL服務器,並執行放回結果。如果想要執行多條statement,使用cmd_query_iter()
Method MySQLConnection.cmd_query_iter(statement)
同cmd_query()方法
statement = 'SELECT 1; INSERT INTO t1 VALUES (); SELECT 2'
for result in cnx.cmd_query_iter(statement):
if 'columns' in result:
columns = result['columns']
rows = cnx.get_rows()
else:
# do something useful with INSERT result
Method MySQLConnection.cmd_refresh(options)
該方法清空緩存,並重設服務器信息。調用該方法的連接需要有RELOAD權限。
Example:
>>> from mysql.connector import RefreshOption
>>> refresh = RefreshOption.LOG | RefreshOption.THREADS
>>> cnx.cmd_refresh(refresh)
Method MySQLConnection.cmd_shutdown()
Asks the database server to shut down. The connected user must have the SHUTDOWN privilege.
Method MySQLConnection.cmd_statistics()
Returns a dictionary containing information about the MySQL server including uptime in seconds and the number of running threads, questions, reloads, and open tables.
Method MySQLConnection.disconnect()
This method tries to send a QUIT command and close the socket. It raises no exceptions.
MySQLConnection.close() is a synonymous method name and more commonly used.
Method MySQLConnection.get_rows(count=None)
該方法返回結果中的rows,如果count為None,則返回所有查詢結果,否則返回指定數量的查詢結果。
返回元組(tuple)的格式:
The row as a tuple containing byte objects, or None when no more rows are available.
EOF packet information as a dictionary containing status_flag and warning_count, or None when the row returned is not the last row.
Method MySQLConnection.get_row()
返回結果為一個元組。
Method MySQLConnection.get_server_info()
Method MySQLConnection.get_server_version()
Method MySQLConnection.is_connected()
測試連接是否可用。
Method MySQLConnection.isset_client_flag(flag)
如果客戶端設置了flag,返回true,否則返回false。
Method MySQLConnection.ping(attempts=1, delay=0)
檢測連接是否依舊可用。
當reconnect設置為true時,進行一次或者多次測試,使用delay設置重試的延遲時間。當連接不可用時,
拋出InterfaceError 錯誤,使用is_connected()方法可以測試連接並且不拋出異常錯誤。
Method MySQLConnection.reconnect(attempts=1, delay=0)
當你預測是由於網絡暫時不可用,導致連接失敗時,使用此函數。attempts嘗試次數應該多一些,間隔delay應該稍微長一些。
Method MySQLConnection.rollback()
回滾當前transaction所進行的所有數據修改。
>>> cursor.execute("INSERT INTO employees (first_name) VALUES (%s)", ('Jane'))
>>> cnx.rollback()
Method MySQLConnection.set_charset_collation(charset=None, collation=None)
還是人家英文文檔寫得比較明白,為了避免誤導,貼在下面了。
This method sets the character set and collation to be used for the current connection. The charset argument can be either the name of a character set, or the numerical equivalent as defined in constants.CharacterSet.
When collation is None, the default collation for the character set is used.
In the following example, we set the character set to latin1 and the collation to latin1_swedish_ci (the default collation for: latin1):
>>> cnx = mysql.connector.connect(user='scott')
>>> cnx.set_charset('latin1')
Specify a given collation as follows:
>>> cnx = mysql.connector.connect(user='scott')
>>> cnx.set_charset('latin1', 'latin1_general_ci')
Method MySQLConnection.set_client_flags(flags)
設置客戶端的flag,如果添加相應flag,則使用正數,否則使用負數。
>>> from mysql.connector.constants import ClientFlag
>>> cnx.set_client_flags([ClientFlag.FOUND_ROWS, -ClientFlag.LONG_FLAG])
>>> cnx.reconnect()
Method MySQLConnection.start_transaction()
該方法接受兩個參數
cnx.start_transaction(consistent_snapshot=bool,
isolation_level=level)
consistent_snapshot默認為false,標示是否使用連續快照;
isolation_level 默認值為None,該參數接受 'READ UNCOMMITTED', 'READ COMMITTED', 'REPEATABLE READ', and 'SERIALIZABLE'這些值.
為了測試transaction是否active,使用in_transaction屬性。
Property MySQLConnection.autocommit
該參數可以標示是否自動提交(This property can be assigned a value of True or False to enable or disable the autocommit feature of MySQL. )
Property MySQLConnection.charset_name
字符集屬性
Property MySQLConnection.collation_name
Property MySQLConnection.connection_id
連接的id,當沒連接時為None
Property MySQLConnection.database
檢索或者設置當前數據庫
>>> cnx.database = 'test'
>>> cnx.database = 'mysql'
>>> cnx.database
u'mysql'
Property MySQLConnection.get_warnings
該屬性標示SQL操作的結果中是否自動接受警告
>>> cnx.get_warnings = True
>>> cursor.execute('SELECT "a"+1')
>>> cursor.fetchall()
[(1.0,)]
>>> cursor.fetchwarnings()
[(u'Warning', 1292, u"Truncated incorrect DOUBLE value: 'a'")]
Property MySQLConnection.in_transaction
標示transaction是否是激活狀態
>>> cnx.start_transaction()
>>> cnx.in_transaction
True
>>> cnx.commit()
>>> cnx.in_transaction
False
Property MySQLConnection.raise_on_warnings
標示警告情況下是否拋出異常
>>> cnx.raise_on_warnings = True
>>> cursor.execute('SELECT "a"+1')
>>> cursor.fetchall()
..
mysql.connector.errors.DataError: 1292: Truncated incorrect DOUBLE value: 'a'
Property MySQLConnection.server_host
返回一個string類型值,代表連接MYSQL的主機名稱或者IP地址
Property MySQLConnection.server_port
返回連接TCP/IP的端口
Property MySQLConnection.sql_mode
設置連接的所有模式
>>> cnx.sql_mode = 'TRADITIONAL,NO_ENGINE_SUBSTITUTION'
>>> cnx.sql_mode.split(',')
[u'STRICT_TRANS_TABLES', u'STRICT_ALL_TABLES', u'NO_ZERO_IN_DATE',
u'NO_ZERO_DATE', u'ERROR_FOR_DIVISION_BY_ZERO', u'TRADITIONAL',
u'NO_AUTO_CREATE_USER', u'NO_ENGINE_SUBSTITUTION']
>>> from mysql.connector.constants import SQLMode
>>> cnx.sql_mode = [ SQLMode.NO_ZERO_DATE, SQLMode.REAL_AS_FLOAT]
>>> cnx.sql_mode
u'REAL_AS_FLOAT,NO_ZERO_DATE'
Property MySQLConnection.time_zone
設置當前時區或者遍歷當前連接所有可用的時區
>>> cnx.time_zone = '+00:00'
>>> cur.execute('SELECT NOW()') ; cur.fetchone()
(datetime.datetime(2012, 6, 15, 11, 24, 36),)
>>> cnx.time_zone = '-09:00'
>>> cur.execute('SELECT NOW()') ; cur.fetchone()
(datetime.datetime(2012, 6, 15, 2, 24, 44),)
>>> cnx.time_zone
u'-09:00'
Property MySQLConnection.unix_socket
只讀屬性,返回用來連接Mysql的Unix socket文件
Property MySQLConnection.user
返回連接服務器的用戶姓名