#1.连接数据库
conn = pymysql.connect(host='localhost',user='root',password='westos',charset=
'utf8',autocommit=True)#自动提交对数据库的操作
#2.创建一个游标,用来给sql发送语句
cur = conn.cursor()
#3.对于数据实现实现增删改查#选择需要进行操作的数据库
conn.select_db('redhat') ##选择要进行操作的数据库
# create_sql = 'create table myuser(name varchar(10) not null,age int)' #创建一个表格
users = [(j,'user' + str(i)) for j in range(20,30) for i in range(10)]
# insert_sql = 'insert into myuser values(%s,%s);' #向表格中插入内容# use = ['user'+ str(i) for i in range(10)]# insert_sql = 'insert into myuser values(%s,%s);'
update_sql = 'update myuser set age=%s where name=%s'# del_sql = 'delete from myuser where name=%s;'# cur.executemany(update_sql,users) # cur.executemany(insert_sql,users) #批量对数据进行修改#查看表中的数据# select_sqli = 'select * from redhat'# res = cur.execute(select_sqli)# print(cur.fetchone())#4.先关闭游标
cur.close()
#5.关闭数据连接
conn.cursor()
数据库上下文管理器
#安全管理器with#1.连接数据库
conn = pymysql.connect(host='localhost',user='root',password='westos',
charset='utf8',autocommit=True,db='redhat')
with conn:
print('is open',conn.open)
#2.创建一个游标,用来给数据库发送sql语句
cur = conn.cursor()
#3.对于数据库进行增删改查操作#显示有多少行记录
res = cur.execute('select * from myuser')
print(res)
#显示每列的详细信息
desc = cur.description
print(desc)
cur.close()