在python中连接mysql和查询数据

1 连接mysql

import pymysql.cursors
# 导入pymysql包
# 连接数据库  connection
= pymysql.connect(host = "localhost", #host是要连接的数据库的IP地址 user = "eric", #user是登陆的账号名,root是最高权限账号 password = "123456", #user账号的密码 db = "45", #需要连接的数据库 charset = "utf8mb4", #设置编码格式 cursorclass = pymysql.cursors.DictCursor) #返回到python的结果,以什么方式储存,DictCursor是字典结构

2 查询数据

try:
#从数据库中获取cursor的数据结构
with connection.cursor() as cursor:
sql = "select * from student"
#可以采用s%代替将要输入的内容,写入select语句中,在execute中输入
cursor.execute(sql)
result = cursor.fetchone()
#fetchone取一条数据,fetchall取符合查询语句的所有数据
print(result)
finally:
connection.close()
#最后关闭连接

3 插入更新删除

基本代码如查询数据一致,查询语句依据需求而定

注意:不同的是在最后需要加commit(),commit才是真正改变数据库,在这之前缓存在内存中

try:
    with connection.cursor() as cursor:
        sql="INSERT INTO `USERS`(`email`,`password`) VALUES (%s,%s)"
        cursor.execute(sql,('webmaster@python.org','very_secret'))
    connection.commit()
#多次commit会影响效率,一般在多条插入后统一commit
#另autocommit开启可以自动触发commit,在connection连接数据库的时候加autocommit=True

 

posted on 2018-08-20 17:37  lvgb  阅读(541)  评论(0编辑  收藏  举报

导航