01、与mysql建立连接,进行一些操作(数据的增删改查)
注意:
python连接mysql,每完成一个cursor最好就要关闭一次cursor。连接可以不用关闭,直到你不再使用当前连接,再关闭连接。python是解释执行,建立数据库连接后,会占用解释器线程,当你不关闭连接时,那么这个线程一直占用,会使执行其他程序变慢。如果不关闭虽然也会过期,但是会较长时间占用mysql宝贵的连接资源。
import pymysql
def main():
# 1.建立连接
con_obj = pymysql.connect(
host='localhost',
user='root',
password='zhuming',
database='localdata',
port=3306,
charset='utf8',
autocommit=True)
# 2.获取游标对象 - 提供数据库操作的上下文
# 注意:游标提供的上下文是事务环境
with con_obj.cursor() as cursor_obj:
# 在这个里面操作数据库
# 操作数据库,执行sql语句:游标对象.execute(sql语句)
# 返回执行结果,这个sql操作影响的行
# 1)创建数据库
# base_name = input('需要创建的数据库的名字(必须是英文):')
# sqlstr = "create database if not exists %s default charset utf8;" % base_name
# result = cursor_obj.execute(sqlstr)
# print(result)
# 2)删除数据库
# base_name = input('需要创建的数据库的名字(必须是英文):')
# cursor_obj.execute('drop database if exists %s;' % base_name)
# 3)使用数据库
cursor_obj.execute('use python1;')
# 4)创建表
# cursor_obj.execute("""create table if not exists tb_person
# (
# pid int not null,
# pname varchar(20) not null,
# page int default 0,
# gender bit default 0,
# primary key(pid)
# );
# """)
# 5)删除表
# cursor_obj.execute("drop table if exists tb_person;")
#
# # 6)增删改
# cursor_obj.execute("""
# insert into tb_person
# (pid,pname,page,gender)
# values
# (1, 'zhangsan', 18, 1),
# (2, 'lisi', 19, 0),
# (3, '小明',20, 1);
# """)
# cursor_obj.execute('delete from tb_person where pid=1;')
# cursor_obj.execute('update tb_person set pname="hhh" where pname="ttt";')
# 7)查:通过游标对象执行查询语句后,查询结果是保存在游标对象中
result = cursor_obj.execute('select pname,pid,page from tb_person')
print(result)
# 游标对象.fetchall() - 获取查询结果,
# 结果是个元祖,元祖中的元素是一个小元祖代表的是每一条记录;小元祖中的元素是每一条记录中每个字段对应的值
# print(cursor_obj.fetchall())
# 通过游标获取结果的时候,取一个就少一个
all_person = cursor_obj.fetchall()
for p in all_person:
print('姓名:', p[0])
print('id:', p[1])
print('age:', p[2])
print(cursor_obj.fetchone()) # none
print(cursor_obj.fetchall()) # ()
# 事务提交
# 注意:如果在建立连接的时候给参数 autocommit赋值为True,后面就不用手动提交了
# con_obj.commit()
# 关闭连接
con_obj.close()
connect_obj = pymysql.connect(
host='localhost',
user='root',
password='zhuming',
port=3306,
charset='utf8',
autocommit=True
)
with connect_obj.cursor(pymysql.cursors.DictCursor) as cursor_obj:
cursor_obj.execute('use python1;')
cursor_obj.execute('select * from tb_person;')
re = cursor_obj.fetchall()
print(re)
connect_obj.close()
if __name__ == '__main__':
main()
02、对象存储(对象数据与数据库数据的交互)
import pymysql
class Mountain:
def __init__(self, name, altitude, location):
self.name = name
self.altitude = altitude
self.location = location
mountains = [
Mountain('雀儿山', 6168, '四川'),
Mountain('半脊峰', 5430, '四川'),
Mountain('玉珠峰', 6178, '青海'),
Mountain('慕士塔格峰', 7546, '新疆'),
Mountain('贡嘎山', 7556, '四川')
]
# obj, 通过类创建对象,类名是唯一的,根据类名创建表名
def insert_obj_database(obj: object, cursor_obj):
class_name = obj.__class__.__name__
table_name = 'tb_' + class_name
# 插入表的时候表的字段根据对象属性来确定
keys = ",".join(obj.__dict__.keys())
# 插入表的时候表的字段的值是根据对象属性的值来确定
values = ""
for value in obj.__dict__.values():
if isinstance(value, str):
values += "'%s'" % value
else:
values += '%s' % value
values += ','
values = values[:-1]
insert_sql = "insert into %s(%s) values (%s);" % (table_name, keys, values)
# 如果表已经存在,那就直接插入,如果没有表,就先创建再插入
try:
cursor_obj.execute(insert_sql)
except pymysql.err.ProgrammingError:
# 创建表。表的字段根据对象的属性来确定,并且要加上类型和约束(约束不一定)
filed = ""
for key in obj.__dict__:
value = obj.__dict__[key]
if isinstance(value, str):
filed += '%s text' % key
else:
filed += '%s float' % key
filed += ','
filed = filed[:-1]
create_sql = "create table %s (%sid int not null auto_increment, %s, primary key(%sid));" % (table_name, table_name[3:6], filed, table_name[3:6])
cursor_obj.execute(create_sql)
cursor_obj.execute(insert_sql)
def main():
# 建立连接
connection_obj = pymysql.connect(
host='localhost',
user='root',
password='zhuming',
port=3306,
charset='utf8',
autocommit=True
)
# 获取游标
# with connection_obj.cursor() as cursor_obj:
with connection_obj.cursor(pymysql.cursors.DictCursor) as cursor_obj:
cursor_obj.execute('use python1;')
# 将对象数据插入数据库中对应的表
# for moun in mountains:
# insert_obj_database(moun, cursor_obj)
# insert_obj_database(Mountain('雪宝顶', 5588, '四川'), cursor_obj)
# 从数据库中取出表的数据并转化成对应的对象
select_sql = "select * from tb_mountain;"
cursor_obj.execute(select_sql)
re = cursor_obj
for item in re:
print(item)
del item['Mouid']
moun = Mountain(**item)
print(moun)
# 关闭连接
connection_obj.close()
if __name__ == '__main__':
main()
网友评论