python语法补遗:
l=[1,2,3,4,5]
取出第一个和最后一个元素语法:
a,*_,b=l
结果:a=1,b=5,_=[2,3,4]
字典:
假如按以下方法实例化对象
可以用字典作为参数,如row,加**,进行调用。加**,表示把字典row拆成对应的参数
dept=Dept(**row)
先在项目的虚拟环境中,升级一下pip
pip install -U pip
修改pip的国内镜像:
在主目录下,创建.pip目录
进入.pip目录,创建pip.conf
添加一下内容:
pip install pymysql
#查看包的依赖项
pip freeze
pip list
pip install mymysql==版本号 指定版本号安装
pip freeze > requirements.txt
pip install -r requirements.txt #不同机器上保证依赖项版本一致
import pymysql
def main():
conn=pymysql.connect(host='10.10.10.131',port=3306,
user='root',password='123456',
db='hrs',charset='utf8'
)
print(conn)
try:
with conn.cursor() as cur:
res=cur.execute('insert into tt_dept values (90,"北京","北京")')
if res==1:
print("添加成功")
conn.commit()
except pymysql.MySQLError as error:
print(error)
conn.rollback()
finally:
conn.close()
if __name__=='__main__':
main()
import pymysql
def main():
conn = pymysql.connect(host='10.10.10.130', port=3306,
user='root', password='123456',
db='hrs', charset='utf8',cursorclass=pymysql.cursors.DictCursor)
try:
with conn.cursor() as cur:
cur.execute('select dno,dname,dloc from tb_dept')
#print(cur.fetchall())
'''
注意以下的区别,cur是游标类型,取过一次,向下移动
cur.fetchone()
cur.fetchmany(2)
cur.fetchall()
默认的游标类型在conn初始化中:cursorclass=Cursor,默认是元组类型,
可以修改为字典类型,便于按字段名提取
'''
'''
for row in cur.fetchall():
print(f'部门编号:{row[0]}')
print(f'部门地点:{row[1]}')
print(f'部门名称:{row[2]}')
'''
for row in cur.fetchall():
print(row['dno'])
print(row['dname'])
print(row['dloc'])
except pymysql.MySQLError as err:
print(err)
finally:
conn.close()
if __name__ == '__main__':
main()
MySQL的参考: