zoukankan      html  css  js  c++  java
  • python 连接MySQL数据库

    # !/usr/bin/python3
    # 2019/9/8
    import pymysql
    
    dbInfo = {
        'host': '127.0.0.1',
        'port': 3306,
        'user': 'root',
        'passwd': '1234',
        'db': 'ajax',#数据库名
        'charset': 'utf8'
    }
    
    
    def select(dbInfo, sql):
        # 打开数据库连接
        db = pymysql.connect(**dbInfo)
        # 使用cursor()方法获取操作游标
        cursor = db.cursor()
        try:
            # 执行SQL语句
            cursor.execute(sql)
            # 获取所有记录列表
            results = cursor.fetchall()
        except:
            print("Error: unable to fetch data")
        finally:
            # 关闭数据库连接
            db.close()
        return results
    
    
    def select(sql):
        # 打开数据库连接
        db = pymysql.connect(**dbInfo)
        # 使用cursor()方法获取操作游标
        cursor = db.cursor()
        try:
            # 执行SQL语句
            cursor.execute(sql)
            # 获取所有记录列表
            results = cursor.fetchall()
        except:
            print("Error: unable to fetch data")
        finally:
            # 关闭数据库连接
            db.close()
        return results
    
    
    def edit(sql):
        # 打开数据库连接
        db = pymysql.connect(**dbInfo)
        # 使用cursor()方法获取操作游标
        cursor = db.cursor()
        try:
            # 执行SQL语句
            cursor.execute(sql)
            # 提交操作
            db.commit()
        except Exception as e:
            print(e)
            print("Error: unable to fetch data")
            db.rollback()
        finally:
            # 关闭数据库连接
            db.close()
    
    
    if __name__ == '__main__':
    
        results=select("select * from bookinfo")
        for row in results:
            print(row)

  • 相关阅读:
    UIViewcontroller生命周期方法
    runtime中的宏定义解释表
    opencv在Mac环境下的安装和配置
    Oracle导入导出
    Oracle触发器详解
    查找表的父表和子表
    Oracle创建表空间
    TRIGGER控制级联更新
    启动Oracle的bat文件
    PL(SQL)块
  • 原文地址:https://www.cnblogs.com/zyt-bg/p/11487330.html
Copyright © 2011-2022 走看看