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()

posted @ 2020-12-29 17:04  告一段落  阅读(63)  评论(0编辑  收藏  举报