Python+MySQL学习之路:二、MySQLdb常用命令

一、连接数据库

MySQLdb提供了connect方法用来和数据库建立连接,接收数个参数,返回连接对象:

conn=MySQLdb.connect(host="localhost",user="root",passwd="jb51",db="test",charset="utf8")
参数解释:

host:数据库主机名.默认是用本地主机
user:数据库登陆名.默认是当前用户
passwd:数据库登陆的秘密.默认为空
db:要使用的数据库名.没有默认值
port:MySQL服务使用的TCP端口.默认是3306
charset:数据库编码

这个连接对象提供了对事务操作的支持,标准的方法:
commit() 提交
rollback() 回滚

示例:

import MySQLdb
def mysql_test():
    conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='test',db='test',port=3306)
    cur=conn.cursor()#获取游标
    cur.execute("select version()")
    data=cur.fetchone()#使用fetchone()返回一条数据库记录
    print 'Database Version:%s' %data
    conn.close()
mysql_test()

二、游标(Cursor)方法

cursor用来执行语句或者过程
callproc(self, procname, args)//用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
execute(self, query, args)//执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
executemany(self, query, args)//执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
nextset(self)//移动到下一个结果集

cursor用来接收返回值的方法

fetchall(self)//接收全部的返回结果行.
fetchmany(self, size=None)//接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据
fetchone(self)//返回一条结果行
//移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果mode='absolute',则表示从结果集的第一行移动value条
scroll(self, value, mode='relative')
rowcount//这是一个只读属性,并返回执行execute()方法后影响的行数
Close()//关闭游标
示列:
import MySQLdb
def mysql_test():
    try:
        #-------------连接数据库------------
        conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='test',db='test',port=3306)
        cur=conn.cursor()
        #-------------创建表格-------------
        sql='create table if not exists test(id int(10),name varchar(20))'
        cur.execute(sql)
        conn.commit()
        cur.execute("show tables")#获取数据库中的表格
        print '创建表格(execute):',cur.fetchall()
        #-------------插入数据-------------
        sql='insert into test values(%s,%s);'
        params=[(1,'hello'),(2,'world')]
        cur.executemany(sql,params)#
        print '插入数据(executemany):成功'
        conn.commit()
        data=cur.execute('select * from test')
        print '获取第一行记录(fetchone):',cur.fetchone()
        cur.scroll(0,'absolute')
        print '获取从游标位置开始的两行记录(fetchmany)',cur.fetchmany(2)
        cur.scroll(0,'absolute')
        print '获取表格行数(rowcount):',cur.rowcount
        print '获取表格所有记录(fetchall)',cur.fetchall()
        #-------------创建过程------------
        sql='''
                create procedure proc(in test int)
                begin
                      select test;
                end;
            '''
        cur.execute("drop procedure if exists proc;")
        cur.execute(sql)#executemany
        conn.commit()
        #-------------调用过程------------
        cur.callproc('proc',(1,))
        print '调用过程proc(callproc):',cur.fetchone()
        #-------------断开连接------------
        cur.close()
        conn.close()
    except :
        conn.rollback()
mysql_test()

执行结果:

Warning (from warnings module):
  File "C:\Python27\Study\MySQLdb", line 9
    cur.execute(sql)
Warning: Table 'test' already exists
创建表格(execute): (('test',),)
插入数据(executemany):成功
获取第一行记录(fetchone): (1L, 'hello')
获取从游标位置开始的两行记录(fetchmany) ((1L, 'hello'), (2L, 'world'))
获取表格行数(rowcount): 2
获取表格所有记录(fetchall) ((1L, 'hello'), (2L, 'world')
调用过程proc(callproc): (1L,)
在写脚本是发现以下错误:

Error Code: 1414. OUT or INOUT argument 1 for routine test.proc is not a variable or NEW pseudo-variable in BEFORE trigger
原因:存储过程最后一个参数是输出参数。因此必须使用一个变量。
ProgrammingError: (2014, "Commands out of sync; you can't run this command now")
原因:数据变更后没有提交事务,参考链接:<a target=_blank href="http://ju.outofmemory.cn/entry/76809">http://ju.outofmemory.cn/entry/76809
</a><pre name="code" class="python">cursor用来执行语句或者过程
三、关闭数据库

cur.close()

conn.close()

四、事务

conn.commit()

conn.rollback()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值