python连接数据库
# 连接数据库
def connection():
try:
db=pymysql.Connection(host='localhost',user='root',password='20214063',database='aa')
print("数据库连接成功!")
except pymysql.err as e:
print("数据库连接失败"+str(e))
finally:
db.close()
python查询
# 执行查询数据操作
def check():
db=pymysql.Connection(host='localhost',user='root',password='20214063',database='aa')
cur=db.cursor()
sqlQuery="select * from person"
try:
cur.execute(sqlQuery)
result=cur.fetchall()
for row in result:
print(f"id:{row[0]} name:{row[1]} age:{row[2]} birth:{row[3]}")
except pymysql.Error as e:
print("查询失败!"+str(e))
db.rollback()
finally:
db.close()
python添加数据
# 执行添加数据操作
def add():
db=pymysql.Connection(host='localhost',user='root',password='20214063',database='aa')
cur=db.cursor()
sqlQuery="insert into person(id,name,age,birth) values(%s,%s,%s,%s)"
value=(23,"小刘",12,"2023-05-21")
try:
cur.execute(sqlQuery,value)
db.commit()
print("数据添加成功!")
except pymysql.Error as e:
print("数据添加失败!"+str(e))
db.rollback()
finally:
db.close()
python修改数据
# 执行修改操作
def update():
db=pymysql.Connection(host='localhost',user='root',password='20214063',database='aa')
cur=db.cursor()
sqlQuery="update person set birth=%s where id=%s"
birth="2023-05-22"
id=23
value=birth,id
try:
cur.execute(sqlQuery,value)
db.commit()
print("数据修改成功!")
except pymysql.Error as e:
print("数据修改失败!"+str(e))
db.rollback()
finally:
db.close()
python删除数据
# 执行删除操作
def delete():
db=pymysql.Connection(host='localhost',user='root',password='20214063',database='aa')
cur=db.cursor()
sqlQuery="delete from person where id=%s"
id=23
value=id
try:
cur.execute(sqlQuery,value)
db.commit()
print("数据删除成功!")
except pymysql.Error as e:
print("数据删除失败!"+str(e))
db.rollback()
finally:
db.close()