import pymysql
# 1.连接mysql数据库的服务
conn = pymysql.Connect(# mysql服务器端的IP,默认127.0.0.1/localhost/真实IP
host ='127.0.0.1',
user ='root',
password ='root',
database ='py',
port =3306,)# 2.创建游标对象
cur = conn.cursor()# 3.编写SQL
sql ='select * from students;'# 4.使用游标对象去调用SQL
cur.execute(sql)# 5.获取查询的结果
result = cur.fetchall()print(result)# 6.关闭游标对象
cur.close()# 7.关闭连接
conn.close()
2. 增加数据、修改数据、删除数据
import pymysql
# 1.连接mysql数据库的服务
conn = pymysql.Connect(# mysql服务器端的IP,默认127.0.0.1/localhost/真实IP
host ='127.0.0.1',
user ='root',
password ='root',
database ='py',
port =3306,)# 2.创建游标对象
cur = conn.cursor()try:# 3.编写SQL# 增加数据
sql ='insert into students values(%s,%s,%s,%s);'
add_data =[0,'wangwu','30','女']# 修改数据
sql1 ='update students set name = %s where name = "zhangsan"'
update_data =['zhaoliu']# 删除数据
sql2 ='delete from students where name = %s'
del_data =['lisi']# 4.使用游标对象去调用SQL
cur.execute(sql,add_data)
cur.execute(sql1,update_data)
cur.execute(sql2,del_data)# 5.提交操作
conn.commit()except Exception as e:print(e)# 数据回滚
conn.rollback()finally:# 6.关闭游标对象
cur.close()# 7.关闭连接
conn.close()