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)

  • 相关阅读:
    关于fill_parent ,wrap_content ,match_parent区别
    开发第六天
    开发第五天
    关于Android创建虚拟机出现Failed to allocate memory: 8解决办法
    第十一周总结
    开发第四天
    开发第三天
    开发第二天
    开发第一天
    用户场景分析
  • 原文地址:https://www.cnblogs.com/zyt-bg/p/11487330.html
Copyright © 2011-2022 走看看