"""
@File:MySQL.py
@Description:
@Author:echohye
@Date:2022/01/28 19:46
"""
import pymysql
'''
@Author:echohye
@Description:连接数据库并创建数据库
@Date:2022-01-28, 周五, 19:47
'''
def connectDB():
db = pymysql.connect(host='localhost', user='root', password='zhy123', port=3306)
cursor = db.cursor()
cursor.execute('select version()')
data = cursor.fetchone()
print(f'Database version:{data}')
cursor.execute('create database spiders default character set utf8mb4')
db.close()
'''
Author:echohye
@Description:创建表
@Date:2022-01-28, 周五, 19:56
'''
def createTable():
db = pymysql.connect(host='localhost', user='root', password='zhy123', port=3306, db='spiders')
cursor = db.cursor()
sql = 'create table if not exists students(id varchar(255) not null,name varchar(255) not null,' \
'age int not null,primary key(id))'
cursor.execute(sql)
db.close()
'''
@Author:echohye
@Description:插入数据
@Date:2022-01-28, 周五, 20:22
'''
def insertData():
id = '10003'
user = 'Mike'
age = 22
db = pymysql.connect(host='localhost', user='root', password='zhy123', port=3306, db='spiders')
cursor = db.cursor()
sql = 'insert into students(id, name, age) values ("'+id+'", "'+user+'", '+str(age)+')'
try:
cursor.execute(sql)
db.commit()
print('插入成功')
except Exception as e:
db.rollback()
print(e.args)
print('插入失败')
finally:
db.close()
'''
@Author:echohye
@Description:更新数据
@Date:2022-01-28, 周五, 21:12
'''
def updateData():
db = pymysql.connect(host='localhost', user='root', password='zhy123', port=3306, db='spiders')
cursor = db.cursor()
sql = "update students set age=19 where name='Mike'"
try:
cursor.execute(sql)
db.commit()
print("successful")
except Exception as e:
db.rollback()
print(e.args)
print("failure")
finally:
db.close()
'''
@Author:echohye
@Description:删除数据
@Date:2022-01-28, 周五, 21:26
'''
def deleteData():
db = pymysql.connect(host='localhost', user='root', password='zhy123', port=3306, db='spiders')
cursor = db.cursor()
sql = "delete from students where name='Mike'"
try:
cursor.execute(sql)
db.commit()
print("successful")
except Exception as e:
db.rollback()
print(e.args)
print("failure")
finally:
db.close()
'''
@Author:echohye
@Description:查询数据
@Date:2022-01-28, 周五, 21:27
'''
def queryData():
db = pymysql.connect(host='localhost', user='root', password='zhy123', port=3306, db='spiders')
cursor = db.cursor()
sql = "select * from students where age>20"
try:
cursor.execute(sql)
query = cursor.fetchall()
print("query:" + query.__str__())
except Exception as e:
print(e.args)
print("failure")
finally:
db.close()
if __name__ == '__main__':
queryData()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!