zoukankan      html  css  js  c++  java
  • python操作mysql

    python操作mysql

    import pymysql
    import prettytable as pt
    
    
    # 连接mysql查看版本
    db = pymysql.connect('localhost','root','root','pyspark')
    
    cursor = db.cursor()
    
    cursor.execute("select version()")
    
    data = cursor.fetchone()
    
    #print(data)
    
    '''
     创建表
    '''
    sql = """
        CREATE TABLE cat (
          name varchar(50),
          age int,
          color varchar(50)
        )
    """
    try:
        res = cursor.execute(sql)
        print('创建成功!')
    except pymysql.err.OperationalError:
        print('表已创建!')
    '''
     插入数据
    '''
    insert_sql = """
        INSERT INTO cat VALUES ('小立',1,'red')
    """
    #cursor.execute(insert_sql)
    #print('插入数据成功!')
    
    '''
    查询数据函数
    '''
    def select(sql):
        cursor.execute(sql)
    
        #查询单行数据
        #res_row = cursor.fetchone()
    
        #print(cursor.description)
        # 查询多行数据
        tb = pt.PrettyTable()
        # 获取表头
        tb_header = []
        for head_col in cursor.description:
            tb_header.append(head_col[0])
        tb.field_names = tb_header
        # 查询所有数据
        res_all = cursor.fetchall()
        # 将数据装载到表格中
        for row in res_all:
            tb.add_row([row[0],row[1],row[2]])
    
        print(tb)
    
    select_sql = '''
        SELECT * FROM student
    '''
    select(select_sql)
    
    db.close()
    
    
  • 相关阅读:
    Centos7 keepalived 修改日志路径
    mysql 双主复制 centos7
    CentOs 7 安装mysql5.7.18(二进制版本)
    oracle、mysql新增字段,字段存在则不处理
    mysql+ibatis 批量插入
    oracle+ibatis 批量插入-支持序列自增
    oracle 批量插入-支持序列自增
    sftp上传
    java
    mysql
  • 原文地址:https://www.cnblogs.com/maguangyi/p/14207597.html
Copyright © 2011-2022 走看看