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()
    
    
  • 相关阅读:
    iOS9 HTTP 不能正常使用的解决办法
    IOS UIWebView的一些用法总结
    顺序查找
    循环队列
    队列的链式存储实现
    栈的链式存储实现
    顺序表的实现
    MessageBox函数
    二分法查找
    冒泡排序
  • 原文地址:https://www.cnblogs.com/maguangyi/p/14207597.html
Copyright © 2011-2022 走看看