python3 操作MySQL数据库

数据库的操作

pip3 install PyMySQL

#!/usr/bin/python3

import pymysql
# 在进行数据的修改更新和删除时,需要进行commit()
'''
数据的获取:
cursor.fetchone(self)
cursor.fetchall(self)
cursor.fetchmany(self,size)
'''
# 打开数据库连接
db = pymysql.connect("localhost", "zz", "123", "my", charset='utf8')
cursor = db.cursor()

# 查看mysql的版本
cursor.execute("SELECT VERSION()")
print("MySQL的版本:%s" % cursor.fetchone())


# 创建一个表my_table 字段有name  sex  number,然后进行数据的插入,查看,最后删除数据表
def runsql(my_sql, cursor=cursor, db=db):
    try:
        cursor.execute(my_sql)
        db.commit()
        if my_sql.lstrip().startswith('create', 0, 8):
            print("数据库表生成成功")
        elif my_sql.lstrip().startswith('drop', 0, 8):
            print("数据库表删除成功")
        elif my_sql.lstrip().startswith('insert', 0, 8):
            print("数据库表插入成功")
        else:
            print("操作成功")
    except:
        db.rollback()
        if my_sql.lstrip().startswith('create', 0, 8):
            print("数据库表生成失败")
        elif my_sql.lstrip().startswith('insert', 0, 8):
            print("数据库表插入失败")
        elif my_sql.lstrip().startswith('drop', 0, 8):
            print("数据库表删除失败")
        else:
            print("操作失败")


def displaysql(sql, my_cursor=cursor):
    my_cursor.execute(sql)
    title_list = [item[0] for item in my_cursor.description]  # 获取表格的字段名称
    for title in title_list:
        print("%-10s" % title, end="")
    print()
    for values in cursor.fetchall():
        for value in values:
            print("%-10s" % value, end="")
        print()


my_table = 'my_table'

print("创建表:")
my_sql = "create table %s (name varchar(20),sex varchar(2),number varchar(10))" % (my_table,)
runsql(my_sql)

print("进行插入")
cursor.execute("select * from %s"%my_table)
table_title = [item[0] for item in cursor.description]   # 获取表格的字段名称
insert_value = [str(i) for i in range(1, len(table_title)+1)]   # 需要插入的值,这里1,2,3...
my_sql = "insert into %s (%s) values (%s)" % (my_table, ",".join(table_title), ",".join(insert_value))
runsql(my_sql)

print("进行查询:")
displaysql("select * from %s" % my_table)

print("进行表删除:")
runsql("drop table if exists %s" % (my_table,))

# 关闭连接
db.close()


'''
MySQL的版本:5.7.25-0ubuntu0.16.04.2
创建表:
数据库表生成成功

进行插入
数据库表插入成功

进行查询:
name      sex       number    
1         2         3      
   
进行表删除:
数据库表删除成功
'''


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值