MySQLdb 模块的使用

来源:互联网 发布:淘宝好评员真的假的 编辑:程序博客网 时间:2024/05/05 17:54
MySQLdb 模块的使用

首先你要有mysql,其次找到对应python版本的python—mysql包下载,注意64位与32的区别

import sys
import MySQLdb

#链接数据库
try:    
    conn = MySQLdb.connect(host = 'localhost',user = '用户名',passwd = '密码',db = 'test(数据库名)'[,charset = 'UTF8'])#如果数据中有中文字符需要设置字符集否则会出现乱码
except Exception,e:                                                                                                         #也可以通过cursor.excute("set name 'GBK")解决
    print e
    sys.exit()

#返回一个游标对象,对数据库的操作都是通过游标进行的
cursor = conn.cursor()

#操作数据库
#创建表
sql = "create table if not exists test(name varchar(128) )"
cursor.execute(sql)

#插入:
sql = "insert into tablename(name) values('%s')%('ahhhhh')" #在sql语句中,字符串需要加''
try:
    cursor.excute(sql)
except Exception,e:
    print e
#多条插入
sql = "insert into tablename(name) values('%s')"
values = (('hehehe'),('ahhhhh'),('xiaoming'))
try:
    cursor.excutemany(sql,values)
except Exception,e:
    print e

#查询:
sql = "select * from tablename"
cursor.excute(sql)
data = cursor.fetchall() #fetchall():将结果集剩余的所有行保存为序列;fetchone():将结果集的下一行保存为序列;fetchmany([size]):将默认长度为size的行保存为序列

if data:
    for x in data:
        print x[0]

#更新
sql = "update tablename set name=%s where name = 'ahhhhh'"   
param = ("23333")    
cursor.execute(sql,param)    

#删除    
sql = "delete from tablename where name=%s"   
param =("23333")    
n = cursor.execute(sql,param)    
print n    
cursor.close()    


#关闭链接:需要分别的关闭指针对象和连接对象.他们有名字相同的方法
cursor.close()
conn.close()


conn的方法:commit() 提交:该方法很重要,如果你对数据库进行了更新,那么一定要使用该方法,否则其他对该数据库的链接无法                      察觉到你的更新;如果你更新了数据库,而又体现不出来,多半就是因为没调用这个函数了。
            rollback() 回滚:可以取消最后一次的commit

其他cursor的方法:
nexset():返回下一个可用的结果集
cursor的属性:description:列描述
              rowcount:行数
              arraysize:行数
0 0