数据库的操作
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
进行表删除:
数据库表删除成功
'''