Python操作Mysql数据库

2021/4/28 2:25:37

本文主要是介绍Python操作Mysql数据库,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、安装 pymysql 库

pip install pymysql

2、操作Mysql数据库

import pymysql

# 打开数据库链接
db = pymysql.connect(host='数据库IP', port='3306', user='用户名', passwd='密码'
                     , database='数据库')

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# 使用execute()方法执行SQL语句
cursor.execute('SQL语句')

# 使用 fetchone() 方法获取一条数据
data_one = cursor.fetchone()

# 使用 fetchall()方法获取所有数据
data_all = cursor.fetchall()


# 除了查询,其他修改操作(增,删,改)
try:
    # 执行SQL语句
    cursor.execute('SQL语句')
    # 提交到数据库执行
    db.commit()
except:
    # 发生错误时回滚
    db.rollback()

# 最后操作
cursor.close()      # 关闭游标
db.close()          # 关闭数据库

3、可以封装成类,和对应的方法

import pymysql

class DBConnection:
    def __init__(self, ip='', port=3306, user='root', passwd='123456', db=''):
        self.ip = ip
        self.port = port
        self.user = user
        self.passwd = passwd
        self.db = db

    # 连接数据库
    def getCon(self):
        try:
            conn =pymysql.connect(
                    host=self.ip,
                    port=self.port,
                    user=self.user,
                    passwd=self.passwd,
                    database=self.db)
            return conn

        except pymysql.Error as e:
            print(f'mysqldb error :{e}')


    #查
    def select(self, sql):
        try:
            con = self.getCon()
            cur = con.cursor()          # 创建游标
            cur.execute(sql)            # 执行语句
            result = cur.fetchall()     # 匹配所有

            return result
        except pymysql.Error as e:
            print(f'mysqldb error :{e}')
        finally:
            cur.close()
            con.close()
    
    # 改
    def update(self, sql):
        try:
            con = self.getCon()
            cur = con.cursor()
            cur.execute(sql)
            con.commit()                # 提交事务
        except pymysql.Error as e:
            con.rollback()
            print(f'mysqldb error :{e}')
        finally:
            cur.close()
            con.close()

    # 增
    def insert(self, sql):
        try:
            con = self.getCon()
            cur = con.cursor()
            cur.execute(sql)
            con.commit()
        except pymysql.Error as e:
            con.rollback()
            print(f'mysqldb error :{e}')
        finally:
            cur.close()
            con.close()

    # 删
    def delete(self, sql):
        try:
            con = self.getCon()
            cur = con.cursor()
            cur.execute(sql)
            con.commit()
        except pymysql.Error as e:
            con.rollback()
            print(f'mysqldb error :{e}')
        finally:
            cur.close()
            con.close()


这篇关于Python操作Mysql数据库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程