• 8.2.3 操作MySQL数据库


      Python访问MySQL数据库可以使用MySQLDb模块,该模块主要方法如下:

        (1)commit():提交事务。

        (2)rollback():回滚事务。

        (3)callproc(self,procname,args):用来执行存储过程,接受的参数为存储过程名和参数列表,反回值为受影响的行数。

        (4)execute(self,query,ages):执行单条SQL语句,接收侧参数为SQL语句中本身和使用的参数列表,返回值为受影响的行数。

        (5)executemany(self,query,args):执行单条SQL语句,但是重复执行参数列表里的参数,返回值为受影响的函数。

        (6)nextset(self):移到下一个结果集。

        (7)fetchall(self):接收全部的返回结果行。

        (8)fetchmany(self,size=None):接收size条返回结果,如果size的值大于返回结果行的数量,则会返回cursor.arraysize条数据。

        (9)fetchone(self):返回一条结果行。

        (10)scroll(self,value,mode='relative'):移动指针到某一行,如果mode=‘relative’,则表示从当前所在行移动value条记录;如果mode='absoulte',则表示从结果集的第一行移动value条记录。

     1 import MySQLdb
     2 
     3 #从MySQL数据库中查询数据
     4 
     5 try:
     6         conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306)
     7         cur = conn.cursor()
     8         cur.execute('select * from user')
     9         cur.close()
    10         conn.close()
    11 except MySQLdb.Error as e:
    12     print('MySQL Error %d:%s'%(e.args[0],e.args[1]))
    13 
    14 
    15 #往MySQL数据库中插入数据
    16 try:
    17     conn = MySQLdb.connect(host='localhost', user='root', passwd='root', db='test', port=3306)
    18     cur = conn.cursor()
    19     cur.execute('create database if not exists python')
    20     conn.select_db('python')
    21     cur.execute('create table test(id int,info varchar(20))')
    22     value=[1,'hi rollen']
    23     cur.execute('insert into test values(%s,%s)',value)
    24     values = []
    25     for i in range(20):
    26         values.append((i,'hi rollen'+str(i)))
    27         
    28     cur.executemany('insert into test values(%s,%s)',values)
    29     cur.execute('update test set info = "I am rollen" where id = 3')
    30     conn.commit()
    31     cur.close()
    32     conn.close()
    33 except MySQLdb.Error as e:
    34     print('MySQL Error %d:%s' % (e.args[0], e.args[1]))
  • 相关阅读:
    gvim : invalid input string
    端口
    Sequence Overview
    vi的使用
    Ubuntu安装CodeBlocks相关问题总结
    中断
    Ubuntu Software Repository
    UVA 12299 RMQ with Shifts
    UVA 12293 Box Game
    POJ 3468 A Simple Problem with Integers (1)
  • 原文地址:https://www.cnblogs.com/avention/p/8972366.html
Copyright © 2020-2023  润新知