MySQLdb 使用简介

MySQLdb 1.2.2 for py2.6  使用简介

先看一个例子:

python MySQLdb 示例 用例 范例 使用说明 python MySQLdb 示例 用例 范例 使用说明
import MySQLdb

def test():
    #建立和数据库系统的连接
    conn=MySQLdb.connect(host='localhost',user='root',passwd='a123456')
    #获取操作游标
    cursor=conn.cursor()
    #执行SQL,创建一个数据库.
    cursor.execute('''create database python''')
    #关闭连接,释放资源
    cursor.close()
    con.close()



python MySQLdb 示例 用例 范例 使用说明 python MySQLdb 示例 用例 范例 使用说明 python MySQLdb Connection对象 Cursor对象
这里面涉及到2个对象,一个是Connection对象(数据库连接对象),MySQLdb.connet()返回的就是该对象;一个是Cursor对象(游标对象),conn.cursor()返回的就是该对象。

一. Connection类(python中一切都可以说是对象,类也是一种对象,所以前面说Connection对象)
*描述:MySQL数据库连接类,它的基类是:_mysql.connection

*方法(只列出部分常用方法):
1. __init__(self, *args, **kwargs)

 初始化方法,接受如下参数:
 (1)host    类型:string    指定目标主机地址

 (2)user    类型:string    指定连接数据库用户名

 (3)passwd   类型:string   指定连接数据所用密码

 (4)db   类型:string   连接的数据库名

 (5)port   类型:integer   连接的端口号

 (6)unix_socket   类型:string   unix_sockete地址

 (7)conv   类型:dict   转换字典,参见MySQLdb.converters

 (8)connect_timeout   类型:integer   连接超时时间

 (9)compress  
 (10)named_pipe  
 (11)init_command   如果有init_command,一旦建立了连接,就会最先执行该sql命令。
 (12)read_default_file  
 (13)read_default_group
   
 (14)cursorclass 指定创建的游标类型
   
 (15)use_unicode
   
 (16)charset   设置编码方式

 (17)sql_mode   设置数据库连接模式

 (18)client_flag   类型:integer

 (19)ssl   类型:dictionary or mapping

 (20)local_infile   类型:integer

  这个对象的初始化参数看起来很多,但不是每一个都必须要有,一般用的参数是前5个,在加上一个charset.

2.cursor(self, cursorclass=None):创建游标,如果cursorClass没有指定,则返回默认的Cursor对象。

3.literal(self, o)

4.set_character_set(self, charset):设置连接字符编码方式

5.set_sql_mode(self, sql_mode):设置数据库模式

6.show_warnings(self):以元组形式返回warnings信息

以下个方法是从基类中继承过来的

7.select_db(self,dbname):作用是指定使用的数据库

8.close():关闭数据库连接

9.commit():提交当前事务

10.rollback():取消当前事务


***********************************************************

游标对象有多种:Cursor,  DictCursor,  SSCursor,  SSDictCursor。

游标对象的类型决定了fetch取出结果返回的类型,如果游标对象是Cursor、SSCursor,返回的数据库中的每一个元组对应就是tuple对象; 否则返返回的就是dict对象.

游标对象虽然有多种,但是它们所具有的方法是大同小异,且它们具有相同的一个基类:BaseCursor

二 BaseCursor类
*描述:游标基类

*数据属性:

    arraysize  使用fechmany()方法一次取出多少条记录(默认值是1)

    connection 游标对象的连接

    description 游标活动状态

    lastrowid      最后更新行的id(如果数据库不支持行id,默认返回None)

    rowcount      最后一次execute()操作返回或影响的行数(默认值-1)

    rownumber  当前游标所在位置(默认值None)


*方法:
1. __init__(self, connection): 初始化函数
2.close(self):关闭游标
3.nextset(self):移动游标至下一结果集,如果没有更多的结果集,返回None;否则返回1
4.execute(self, query, args=None):执行一个sql语句
5.executemany(self, query, args):多次执行一条sql语句(参数不同)
6.callproc(self, procname, args=()):执行存储过程procname

游标对象其他共同的方法:

1.fetchone(self):得到结果集的下一行

2.fetchmany(self, size=None):得到结果的下几行,如果size=None,arraysize将被使用

3.fetchall(self):返回结果集中剩下的所有行

一些使用例子:

插入和更新数据,需要注意的是,要记得commit,否则插入的数据是不会写入数据库表的。

python MySQLdb 插入数据 示例 用例 范例 使用说明 python MySQLdb 插入数据 示例 用例 范例 使用说明
import MySQLdb
def test1():
    conn=MySQLdb.connect(host='localhost',user='root',passwd='a123456')
    cursor=conn.cursor()
    cursor.execute('''create database if not exists python''')
    #选择数据库
    conn.select_db('python')
    #创建一个数据表
    cursor.execute('''create table test(id int,info varchar(100))''')
    value=[1,'inserted ?']
    #插入一条记录
    cursor.execute('insert into test values(%s,%s)',value)
    #cursor.execute('insert into test values(1,"inserted")')
    values=[]
    #生成插入参数值
    for i in range(20):
        values.append((i,'Hello mysqldb,I am recoer'+str(i)))
    #插入多条记录
    cursor.executemany('insert into test values(%s,%s)',values)
    cursor.close()  
    conn.commit()#必须有,否则插入的数据无效
    conn.close()  

查询数据

python MySQLdb 查询数据 示例 用例 范例 使用说明 python MySQLdb 查询数据 示例 用例 范例 使用说明
import MySQLdb
def test2():
    conn=MySQLdb.connect(host='localhost',user='root',passwd='a123456')
    cursor=conn.cursor()
    conn.select_db('python')
    count=cursor.execute('select *from test')
    print '总共有 %s 条记录'%count
    #获取一条记录,每条记录做为一个元组返回
    print '只获取一条记录:'
    result=cursor.fetchone()
    print result
    #获取5条记录,注意由于之前执行有了fetchone(),所以游标已经指到第二条记录了,也就是从第二条开始的所有记录
    print '只获取5条记录:'
    results=cursor.fetchmany(5)
    for r in results:
        print r
    cursor.close()
    conn.close()

查询指定的m,n行数据

python MySQLdb 查询多条数据 示例 用例 范例 使用说明 python MySQLdb 查询多条数据 示例 用例 范例 使用说明
import MySQLdb
def test3():
    conn=MySQLdb.connect(host='localhost',user='root',passwd='a123456')
    cursor=conn.cursor(MySQLdb.cursors.DictCursor)
    conn.select_db('python')
    count=cursor.execute('select *from test')
    count=cursor.execute('select *from test')
    print '总共有 %s 条记录'%count
    m,n=10,15
    #取第11条至第15条数据
    cursor.rownumber=m
    results=cursor.fetchmany(n-m)
    for r in results:
        print r
    cursor.close()
    conn.close()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值