打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
MySQL与Python交互

关于MySQL推荐一本书MySQL必知必会

首先安装第三方模块(ubuntu下Python2)

sudo apt-get install python-mysql

假设有一数据库test1,里面有一张产品信息表products,向其中插入一条产品信息,程序如下:

# -*- coding: utf-8 -*-import MySQLdbtry:    conn=MySQLdb.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8')    cs1=conn.cursor()    count=cs1.execute("insert into products(prod_name) values('iphone')")    print count    conn.commit()    cs1.close()    conn.close()except Exception,e:    print e.message

Connection对象:用于建立与数据库的连接
        创建对象:调用connect()方法
conn=connect(参数列表)
    参数host:连接的mysql主机,如果本机是'localhost'
    参数port:连接的mysql主机的端口,默认是3306
    参数db:数据库的名称
    参数user:连接的用户名
    参数password:连接的密码
    参数charset:通信采用的编码方式,默认是'gb2312',要求与数据库创建时指定的编码一致,否则中文会乱码

对象的方法
    close()关闭连接
    commit()事务,所以需要提交才会生效
    rollback()事务,放弃之前的操作
    cursor()返回Cursor对象,用于执行sql语句并获得结果

Cursor对象:执行sql语句
    创建对象:调用Connection对象的cursor()方法
    cursor1=conn.cursor()

对象的方法
    close()关闭
    execute(operation [, parameters ])执行语句,返回受影响的行数
    fetchone()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组
    next()执行查询语句时,获取当前行的下一行
    fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回
    scroll(value[,mode])将行指针移动到某个位置
        mode表示移动的方式
        mode的默认值为relative,表示基于当前行移动到value,value为正则向下移动,value为负则向上移动
        mode的值为absolute,表示基于第一条数据的位置,第一条数据的位置为0

修改/删除:

# -*- coding: utf-8 -*-import MySQLdbtry:    conn=MySQLdb.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8')    cs1=conn.cursor()    # 修改    count=cs1.execute("update products set prod_name='xiaomi' where id=6")   # 删除  count=cs1.execute("delete from products where id=6")  print count     conn.commit()     cs1.close()     conn.close()except Exception,e:    print e.message

参数化:插入一条数据

# -*- coding: utf-8 -*-import MySQLdbtry:    conn=MySQLdb.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8')    cs1=conn.cursor()    prod_name=raw_input("请输入产品名称:")    params=[prod_name]    count=cs1.execute('insert into products(sname) values(%s)',params)    print count    conn.commit()    cs1.close()    conn.close()except Exception,e:    print e.message

查询一条

# -*- coding: utf-8 -*-import MySQLdbtry:    conn=MySQLdb.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8')    cs1=conn.cursor()    cur.execute('select * from products where id=2')    result=cur.fetchone()    print result    conn.commit()     cs1.close()     conn.close() except Exception,e:     print e.message

查询多条

# -*- coding: utf-8 -*-import MySQLdbtry:    conn=MySQLdb.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8')    cs1=conn.cursor()    cur.execute('select * from prod_name')    result=cur.fetchall()    print result    conn.commit()     cs1.close()     conn.close() except Exception,e:     print e.message

封装:观察前面的程序发现,除了sql语句及参数不同,其它语句都是一样的,可以进行封装然后调用

# -*- coding: utf-8 -*-import MySQLdbclass MysqlHelper():    def __init__(self,host,port,db,user,passwd,charset='utf8'):        self.host=host        self.port=port        self.db=db        self.user=user        self.passwd=passwd        self.charset=charset    def connect(self):        self.conn=MySQLdb.connect(host=self.host,port=self.port,db=self.db,user=self.user,passwd=self.passwd,charset=self.charset)        self.cursor=self.conn.cursor()    def close(self):        self.cursor.close()        self.conn.close()    def get_one(self,sql,params=()):        result=None        try:            self.connect()            self.cursor.execute(sql, params)            result = self.cursor.fetchone()            self.close()        except Exception, e:            print e.message        return result    def get_all(self,sql,params=()):        list=()        try:            self.connect()            self.cursor.execute(sql,params)            list=self.cursor.fetchall()            self.close()        except Exception,e:            print e.message        return list    def insert(self,sql,params=()):        return self.__edit(sql,params)    def update(self, sql, params=()):        return self.__edit(sql, params)    def delete(self, sql, params=()):        return self.__edit(sql, params)    def __edit(self,sql,params):        count=0        try:            self.connect()            count=self.cursor.execute(sql,params)            self.conn.commit()            self.close()        except Exception,e:            print e.message        return count

保存为MysqlHelper.py文件。

调用类添加

# -*- coding: utf-8 -*-from MysqlHelper import *sql='insert intoproducts(prod_name,price) values(%s,%s)'prod_name=raw_input("请输入产品名称:")price=raw_input("请输入单价:")params=[prod_name,price]mysqlHelper=MysqlHelper('localhost',3306,'test1','root','mysql')count=mysqlHelper.insert(sql,params)if count==1:    print 'ok'else:    print 'error'

调用类查询查询

# -*- coding: utf-8 -*-from MysqlHelper import *sql='select prod_name,price from products order by id 'helper=MysqlHelper('localhost',3306,'test1','root','mysql')one=helper.get_one(sql)print one
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
python实现的MySQL增删改查操作实例小结
Python数据库连接池相关示例详细介绍
Python操作Mysql - 课程 - 从此学习网
pymysql 库的正确打开姿势
Python-Mysql在测试过程中的应用
Python接口测试之对MySQL的增、删、改、查操作(五)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服