【Python学习之十】操作数据库

环境
  虚拟机:VMware 10
  Linux版本:CentOS-6.5-x86_64
  客户端:Xshell4
  FTP:Xftp4
  python3.6

操作mysql数据库

1、安装pymysql模块
pip install pymysql
或者
conda install pymysql

2、使用示例 

相对java 是非常简单的

'''
Created on 2019年5月8日

@author: Administrator
'''
import pymysql as db
#创建连接
conn=db.connect('134.32.123.101','root','123456','spark')
#获取游标
cursor=conn.cursor()
#游标执行语句
cursor.execute('select * from person')
#获取一条记录
pn=cursor.fetchone()
print(pn)#结果是一个元组:('1', 'zhangsan', 18)
#获取所有元素
pns=cursor.fetchall()
print(pns)#(('2', 'wangwu', 12), ('3', 'lisi', None))
#关闭连接
conn.close()

3、数据库操作工具类

#coding:utf-8
import  pymysql

class MysqlHelper(object):
    config={
        "host":"localhost",
        "user":"root",
        "password":"123456",
        "db":"demo",
        "charset":"utf8"
    }
    def __init__(self):
        self.connection=None
        self.cursor=None

    # 从数据库表中查询一行数据 select count(*) from emp
    def getOne(self,sql,*args):
        try:
            self.connection = pymysql.connect(**MysqlHelper.config)
            self.cursor = self.connection.cursor()
            self.cursor.execute(sql,args)
            return self.cursor.fetchone()
        except Exception as ex:
            print(ex,ex)
        finally:
            self.close()

    # 从数据库表中查询多行数据
    def getList(self,sql,*args):
        try:
            self.connection = pymysql.connect(**MysqlHelper.config)
            self.cursor = self.connection.cursor()
            self.cursor.execute(sql,args)
            return self.cursor.fetchall()
        except Exception as ex:
            print(ex,ex)
        finally:
            self.close()

    # 对数据库进行增,删,改
    def executeDML(self,sql,*args):
        try:
            self.connection = pymysql.connect(**MysqlHelper.config)
            self.cursor = self.connection.cursor()
            self.cursor.execute(sql,args)#  返回 sql语句执行之后影响的行数
            new_id = self.connection.insert_id() # 返回系统刚刚自动生成的id
            self.connection.commit();
            return new_id
        except Exception as ex:
            self.connection.rollback()
            print(ex,ex)
        finally:
            self.close()

    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.close()

if __name__ == "__main__":
    helper = MysqlHelper()
    print(helper.executeDML("delete from dept where deptno=%s",80))
#     print(helper.executeDML("insert into dept values(%s,%s,%s)","80","admin","beijing"))

 

参考:
Python学习笔记

posted @ 2019-05-08 15:00  cac2020  阅读(277)  评论(0编辑  收藏  举报