设为首页 收藏本站
查看: 517|回复: 0

[经验分享] MySQL Python教程(3)

[复制链接]

尚未签到

发表于 2015-4-27 10:39:58 | 显示全部楼层 |阅读模式
  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
  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。
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-61148-1-1.html 上篇帖子: [MAC] Load Crypto.Cipher.ARC4 Failed, Use Pure Python Instead. 下篇帖子: python main函数
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表