MySQL Python教程(3)


Class cursor.MySQLCursor

具體方法和屬性如下:
Constructor cursor.MySQLCursor
Method MySQLCursor.callproc(procname, args=())
Method MySQLCursor.close()
Method MySQLCursor.execute(operation, params=None, multi=False)
Method MySQLCursor.executemany(operation, seq_params)
Method MySQLCursor.fetchall()
Method MySQLCursor.fetchmany(size=1)
Method MySQLCursor.fetchone()
Method MySQLCursor.fetchwarnings()
Method MySQLCursor.stored_results()
Property MySQLCursor.column_names
Property MySQLCursor.description
Property MySQLCursor.lastrowid
Property MySQLCursor.statement
Property MySQLCursor.with_rows

 

Constructor cursor.MySQLCursor
使用MySQLConnection對象來初始化

Method MySQLCursor.callproc(procname, args=())
調用procname程序,args要包含所有需要用到的參數。返回值類型為MySQLCursorBuffered。

# Definition of the multiply stored procedure:
# CREATE PROCEDURE multiply(IN pFac1 INT, IN pFac2 INT, OUT pProd INT)
# BEGIN
# SET pProd := pFac1 * pFac2;
# END
>>> args = (5, 5, 0) # 0 is to hold value of the OUT parameter pProd
>>> cursor.callproc('multiply', args)
('5', '5', 25L)

Method MySQLCursor.close()
每次使用完cursor后,調用該函數關閉。

Method MySQLCursor.execute(operation, params=None, multi=False)
該函數用來提出針對數據庫的操作。params是操作中的參數。
insert = (
"INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
"VALUES (%s, %s, %s, %s)")
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert, data)
select = "SELECT * FROM employees WHERE emp_no = %(emp_no)s"
cursor.execute(select, { 'emp_no': 2 })

如果multi參數設置為true,則可以執行多條語句,返回值為指向每個結果的迭代器。
operation = 'SELECT 1; INSERT INTO t1 VALUES (); SELECT 2'
for result in cursor.execute(operation):
if result.with_rows:
print("Statement '{}' has following rows:".format(
result.statement))
print(result.fetchall())
else:
print("Affected row(s) by query '{}' was {}".format(
result.statement, result.rowcount))

Method MySQLCursor.executemany(operation, seq_params)
數據庫操作operation會執行多次,直至seq_params中所有參數執行完畢。
data = [
('Jane', date(2005, 2, 12)),
('Joe', date(2006, 5, 23)),
('John', date(2010, 10, 3)),
]
stmt = "INSERT INTO employees (first_name, hire_date) VALUES (%s, %s)"
cursor.executemany(stmt, data)

Method MySQLCursor.fetchall()
返回查詢的結果集合。
>>> cursor.execute("SELECT * FROM employees ORDER BY emp_no")
>>> head_rows = cursor.fetchmany(size=2)
>>> remaining_rows = cursor.fetchall()

Method MySQLCursor.fetchmany(size=1)
返回接下來的size個查詢結果,如果沒有足夠的結果,則返回空的list。

Method MySQLCursor.fetchone()
返回接下來的一個查詢結果,該函數在fetchamany()和fetchalll()中調用。
# Using a while-loop
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
print(row)
row = cursor.fetchone()
# Using the cursor as iterator
cursor.execute("SELECT * FROM employees")
for row in cursor:
print(row)

Method MySQLCursor.fetchwarnings()
設置get_warnings為true后,能通過該函數獲取警告元組。
>>> cnx.get_warnings = True
>>> cursor.execute('SELECT "a"+1')
>>> cursor.fetchall()
[(1.0,)]
>>> cursor.fetchwarnings()
[(u'Warning', 1292, u"Truncated incorrect DOUBLE value: 'a'")]

Method MySQLCursor.stored_results()
調用 callproc()后,產生的結果集合可以用該函數獲取。
>>> cursor.callproc('sp1')
()
>>> for result in cursor.stored_results():
... print result.fetchall()
...
[(1,)]
[(2,)]

Property MySQLCursor.column_names
只讀屬性。返回一個Unicode編碼的string,為結果集合的列名稱。
cursor.execute("SELECT last_name, first_name, hire_date "
"FROM employees WHERE emp_no = %s", (123,))
row = dict(zip(cursor.column_names, cursor.fetchone())
print("{last_name}, {first_name}: {hire_date}".format(row))

Property MySQLCursor.description
返回cursor結果集合的描述。

import mysql.connector
from mysql.connector import FieldType
...
cursor.execute("SELECT emp_no, last_name, hire_date "
"FROM employees WHERE emp_no = %s", (123,))
for i in range(len(cursor.description)):
print("Column {}:".format(i+1))
desc = cursor.description[i]
print("column_name = {}".format(desc[0]))
print("type = {} ({})".format(desc[1], FieldType.get_info(desc[1])))
print("null_ok = {}".format(desc[6]))
print("column_flags = {}".format(desc[7]))

輸出如下:
Column 1:
column_name = emp_no
type = 3 (LONG)
null_ok = 0
column_flags = 20483
Column 2:
column_name = last_name
type = 253 (VAR_STRING)
null_ok = 0
column_flags = 4097
Column 3:
column_name = hire_date
type = 10 (DATE)
null_ok = 0
column_flags = 4225


Property MySQLCursor.lastrowid
返回最近修改的列的id值。

Property MySQLCursor.statement
返回上一次的執行結果。

Property MySQLCursor.with_rows
如果返回結果提供rows,該值為true。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM