美文网首页
python 操作MySql数据库

python 操作MySql数据库

作者: 觉释 | 来源:发表于2020-06-09 09:30 被阅读0次

    我的环境Python3.7 Mysql5,7

    1、安装MySql

    pip3 install PyMySQL
    

    2、MySql 连接数据

    import pymysql
    
    db = pymysql.connect("127.0.0.1","root","root","db" ) # 打开数据库连接
    cursor.execute("SELECT VERSION()")                    # 使用 execute() 方法执行 SQL 查询
    data = cursor.fetchone()                              # 使用 fetchone() 方法获取单条数据
    print ("Database version : %s " % data)
    db.close()                                            # 关闭数据库连接
    
     更多参数
    import pymysql
    
    conn = pymysql.connect(
            host='127.0.0.1', user='root', password="root",
            database='db', port=3306, charset='utf-8',
    )
    
    cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
    
    
    

    3、插入数据

    import pymysql
    
    def insert_db(insert_sql):
        """插入"""
        # 建立数据库连接
         host="127.0.0.1",
            port=3306,
            user="root",
            passwd="root",
            db="db"
        )
        # 通过 cursor() 创建游标对象
        cur = db.cursor()
        try:
            # 使用 execute() 执行sql
            cur.execute(insert_sql)
            # 提交事务
            db.commit()
        except Exception as e:
            print("操作出现错误:{}".format(e))
            # 回滚所有更改
            db.rollback()
        finally:
            # 关闭游标
            cur.close()
            # 关闭数据库连接
            db.close()
    
    insert_sql = 'insert into user( username, password) values( "张飞", "500")'
    insert_db(insert_sql)
    

    4、查询操作

    import pymysql
    
    def select_db(select_sql):
        """查询"""
        # 建立数据库连接
        db = pymysql.connect(
            host="127.0.0.1",
            port=3306,
            user="root",
            passwd="root",
            db="db"
        )
        # 通过 cursor() 创建游标对象,并让查询结果以字典格式输出
        cur = db.cursor(cursor=pymysql.cursors.DictCursor)
        # 使用 execute() 执行sql
        cur.execute(select_sql)
        # 使用 fetchall() 获取所有查询结果
        data = cur.fetchall()
        # 关闭游标
        cur.close()
        # 关闭数据库连接
        db.close()
        return data
    
    select_sql = 'select * from user whereusername="小张"'
    print(select_db(select_sql))
    

    5、删除操作

    import pymysql
    
    def delete_db(delete_sql):
        """删除"""
        # 建立数据库连接
        db = pymysql.connect(
             host="127.0.0.1",
            port=3306,
            user="root",
            passwd="root",
            db="db"
        )
        # 通过 cursor() 创建游标对象
        cur = db.cursor()
        try:
            # 使用 execute() 执行sql
            cur.execute(delete_sql)
            # 提交事务
            db.commit()
        except Exception as e:
            print("操作出现错误:{}".format(e))
            # 回滚所有更改
            db.rollback()
        finally:
            # 关闭游标
            cur.close()
            # 关闭数据库连接
            db.close()
    
    delete_sql = 'delete from  user whereid = 1'
    delete_db(delete_sql)
    

    6、更新操作

    import pymysql
    
    def update_db(update_sql):
        """更新"""
        # 建立数据库连接
        db = pymysql.connect(
             host="127.0.0.1",
            port=3306,
            user="root",
            passwd="root",
            db="db"
        )
        # 通过 cursor() 创建游标对象
        cur = db.cursor()
        try:
            # 使用 execute() 执行sql
            cur.execute(update_sql)
            # 提交事务
            db.commit()
        except Exception as e:
            print("操作出现错误:{}".format(e))
            # 回滚所有更改
            db.rollback()
        finally:
            # 关闭游标
            cur.close()
            # 关闭数据库连接
            db.close()
    
    update_sql = 'update user set username = "小例子" WHERE id = 1'
    update_db(update_sql)
    

    相关文章

      网友评论

          本文标题:python 操作MySql数据库

          本文链接:https://www.haomeiwen.com/subject/cinjtktx.html