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)

  • 相关阅读:
    oracle 添加用户
    oracle---存储结构及其之间的关系和创建数据库
    oracle---临时表空间
    对字符串进行加密解密知识
    面向对象---函数重复---原型
    Ajax
    sqlHelper+app.config
    sqlHelper ---转载
    web.config中的连接字符串 ---关于 providerName 特性---转载
    SQL中的cast()函数--转载
  • 原文地址:https://www.cnblogs.com/zyt-bg/p/11487330.html
Copyright © 2011-2022 走看看