Python 连接数据库 day5

import pymysql
#连接数据库,port必须是int型,字符编码是utf8,不能是utf-8,password必须是字符串
conn = pymysql.connect(host='数据库ip',user='user1',password='123456',
                       db='db_name',port=3306,charset='utf8',autocommit=True)#建立连接
cur= conn.cursor()#建立游标,可以把游标当作仓库管理员

cur.execute('show tables;')#只是帮你执行sql语句
print(cur.fetchall())#获取sql语句执行的结果
sql1="select * from app_student limit 5;"
cur.execute(sql1)
print(cur.fetchall())#取所有数据
sql2="select * from app_student where name='smh'"
cur.execute(sql2)
print(cur.fetchone())#只取一条,若返回结果有多条,只取第一条
sql3="select * from app_student where name ='hhh'"
cur.execute(sql3)
print(cur.fetchmany(3))#取几条
sql4="insert app_student ( `name`, `sex`, `age`, `addr`, `grade`, `phone`, `gold`) " \
       "values ( 'test', 'girl', '18', 'beijing', 'jxz', '13121211111', '100');"
cur.execute(sql4)
conn.commit()
#提交,update、delete、insert这些修改数据库的语句,执行需要commit才能成功
#在connect中添加autocommit=True则自动提交

cur.close()#关闭游标
conn.close()#关闭连接,使用完了要关连接,不然会占数据库

 将sql执行返回结果转为字典格式:

import pymysql
#连接数据库,port必须是int型,字符编码是utf8,不能是utf-8,password必须是字符串
conn = pymysql.connect(host='118.24.3.40',user='jxz',password='123456',
                       db='jxz',port=3306,charset='utf8',autocommit=True)#建立连接
cur=conn.cursor(pymysql.cursors.DictCursor)#传一个游标类型,可展示为字典
sql5= "select * from app_student where name='hhh'"
cur.execute(sql5)
print(cur.fetchmany(3))
cur.close()
conn.close()


结果为:
[{'id': 328, 'name': 'hhh', 'sex': 'girl', 'age': 18, 'addr': '河南省济源市北海大道32号', 'grade': '天蝎座', 'phone': '18612539012', 'gold': 100},
{'id': 345, 'name': 'hhh', 'sex': 'girl', 'age': 18, 'addr': '河南省济源市北海大道32号', 'grade': '天蝎座', 'phone': '18612539012', 'gold': 100},
{'id': 347, 'name': 'hhh', 'sex': 'girl', 'age': 18, 'addr': '河南省济源市北海大道32号', 'grade': '天蝎座', 'phone': '18612539012', 'gold': 100}]

猜你喜欢

转载自www.cnblogs.com/candysalty/p/11074488.html