python连接数据库
import pymysql from pymysql.constants import CLIENT ''' pymysql 执行多条SQL语句 8.0版本之后需要在建立连接的时候添加参数client_flag = CLIENT.MULTI_STATEMENTS ''' # 打开数据库连接 db = pymysql.connect(host='localhost',user='root', passwd='root',db='logindemo',charset='utf8',port=3306, client_flag = CLIENT.MULTI_STATEMENTS) # 获取操作游标,数据库句柄,传递操作 cu = db.cursor() db.ping(reconnect = True) # 检查连接是否断开,断开重连 # 构造SQL语句 ,SQL语句中如果出现数据库关键字则用反引号引起 sqlStr = ''' update user set `uname`='lll' where uid=1; select * from user; ''' # 执行SQL语句 cu.execute(sqlStr) # 如果涉及到数据库的修改,则需要提交 db.commit() data = cu.fetchone() # 返回第一条数据 ,类型为元组 print(data) # 第一条 # # data = cu.fetchone()# # # print(data) # 接着上条数据,返回一条数据 # datas = cu.fetchall() # 返回所有结果 ,类型为元组 # 关闭数据库连接 db.close()