python---操作mysql


1、操作数据库流程:


(1)流程:安装第三方模块--创建连接--创建游标--执行语句--获取结果--关闭游标--关闭连接


(2)注意事项:密码必须为字符,端口号必须为int类型, 创建连接是端口号有默认值为3306 可以不写


(3)创建连接其他字段:charset="utf8"非utf-8 用于解决中文乱码问题,autocommit=True 为自动提交,用于更新数据库内容时



import pymysql
host = "110.40.129.50"
username="jxz"
password="123456" ##必须是字符串
db="jxz" #数据库
port=3306 #端口号 默认 int 必须写int类型
charset="utf8" #字符集
#一句话来说就是让计算机认识各种字符 英文 汉语等等。。。ascii
#gb2312 国标
#gbk 中国计算机认识了
#unicode 万国码
#utf-8

conn=pymysql.connect(host=host,user=username,
passwd=password,db=db,port=port,charset=charset)#连接数据库 autocmmit=True自动提交到数据库
cur=conn.cursor()#建立游标
#cur=conn.cursor(pymysql.cursors.DictCursor)#指定游标结果变成字典
sql="select * from students3_info;"
cur.execute(sql)#执行sql语句
print(cur.fetchall())#所有的结果 #结果返回的是二维数组
# print(cur.fetchone())#获取一条数据结果,确定是一条可以用,唯一的那种
# for c in cur:#执行循环游标,也是可以获取所有数据,数据量大的时候
# print(c) #循环一次一条
# print(cur.fetchmany(10)) 想获取几条就获取几条
# print(cur.rowcount) 查看查询多少条
cur.close() #关掉游标
conn.close() #关掉连接

#登录,格式化方式
uname=input("username:")
# sql= "select * from students3_info where name ='%s'"% uname #sql自己拼好的,格式化好了,int类型加引号
# print(sql)未执行1
#cur.execute(sql.[uname,age])
#sql= "select * from students3_info where name =%s and age =%s;" #%s变量,自动就加引号了
# print(sql)未执行2 可以防sql注入(安全攻击的一种手段)




# insert_sql = "insert into students3_info (name,age,password) values ('周周',18,'sdfsfsfd');"
# cur.execute(insert_sql) #执行aql
# conn.commit()#提交数据库
# conn.rollback()#回滚
# print(cur.fetchall())#所有的结果
# cur.close()
# conn.close()

# update_sql = "update students3_info set name='xxx_xiugai' where id=3;"
# cur.execute(update_sql) #执行aql
# conn.commit()#提交数据库
# conn.rollback()#回滚
# print(cur.fetchall())#所有的结果
# cur.close()
# conn.close()

# delete_sql = "delete from students3_info where id = 5; "
# cur.execute(delete_sql) #执行aql
# conn.commit()#提交数据库
# #conn.rollback()#回滚
# print(cur.fetchall())#所有的结果
#
# cur.close()
# conn.close()

参考:

例一、查询语句


# 引用
import pymysql
ip="xxx.xx.xxx.xx"
user="jxz"
password="123456" #必须是字符串
db="jxz"
port=3306 # 必须写int类型
# 创建连接
connect=pymysql.connect(host=ip,user=user,password=password,db=db,port=port,charset="utf8")
# 创建游标
cursor=connect.cursor()
sql="select * from test1"
# 执行语句
cursor.execute(sql)
# 获取结果
res=cursor.fetchall()
print(res)

# 关闭游标
cursor.close()
# 关闭连接
connect.close()

例二、插入 修改 删除语句:执行--提交/回滚


(1)提交:connect.commit()


(2)回滚:connect.rollback()


import pymysql
ip="xxx.xx.xxx.xx"
user="jxz"
password="123456" #必须是字符串
db="jxz"
port=3306 # 必须写int类型
# 创建连接
connect=pymysql.connect(host=ip,user=user,password=password,db=db,port=port,charset="utf8")
# 创建游标
cursor=connect.cursor()
# sql="select * from test1"
# 修改语句需要提交
sql="update test1 set name ='lxp' where id =1"
# 执行语句
cursor.execute(sql)
connect.commit()
# 获取结果
res=cursor.fetchall()
print(res)

# 关闭游标
cursor.close()
# 关闭连接
connect.close()

2、fetchall,fetchone,fetchmany


(1)cursor.fetchall()获取sql执行所有结果 始终返回一个二维数组


sql="select * from test1"
# 执行语句
cursor.execute(sql)
res=cursor.fetchall()
结果:((1, 'lxp', 0, '13555768930'), (2, '隋春林', 0, '13245678909'), (4, '李宇春', 1, '12345678901'), (8, '李宇春1', 1, '12245678901'))

(2)cursor.fetchone():获取一条


sql="select * from test1"
# 执行语句
cursor.execute(sql)
res=cursor.fetchone()
结果:(1, 'lxp', 0, '13555768930')

(3)cursor.fetchmany(n):获取n条,返回也是二维数组


sql="select * from test1"
# 执行语句
cursor.execute(sql)
res=cursor.fetchmany(2)
结果:((1, 'lxp', 0, '13555768930'), (2, '隋春林', 0, '13245678909'))

3、获取表里字段描述


cursor.execute(sql)
print(cursor.description)

4、返回字典格式设置:游标里面指定:pymysql.cursor.DictCursor


cursor=connect.cursor(pymysql.cursors.DictCursor)
# 修改语句需要提交
# sql="update test1 set name ='lxp' where id =1"
sql="select * from test1"
# 执行语句
cursor.execute(sql)
res=cursor.fetchone()
结果:{'id': 1, 'name': 'lxp', 'sex': 0, 'phone': '13555768930'}

5.2大文件读取


读取数据量比较大的时候,可以直接循环游标,每次取得就是表里的一条数据


sql="select * from test1"

# 执行语句
cursor.execute(sql)
for c in cursor:
print(c)

5.3函数封装


1、代码


import pymysql
def op_mysql(mysql_info:dict,sql:str,all=True):
connect=pymysql.connect(**mysql_info)
cursor=connect.cursor()
cursor.execute(sql)
res=None
if sql.strip().lower().startswith("select"):
if all:
res=cursor.fetchall()
else:
res=cursor.fetchone()
return res
if __name__ == '__main__':
mysql_info={"host":"xxx.xx.xxx.xx","user":"jxz",
"password":"123456" ,"db":"jxz","port":3306,
"autocommit":True,"charset":"utf8"}
sql1="select * from test1"
sql2="select * from test1 where id =1"
print(op_mysql(mysql_info,sql1))
print(op_mysql(mysql_info,sql2, False))

2、*与**的作用


一个* 对应的列表 将列表解开 对应到形参上


def add(a,b):
return a+b

l=[1,2]
print(add(*l))
结果:3

两个* 对应字典,将字典解开,对应函数形参,字典的key与函数的形参需要命名一致


def add(a,b):
return a+b
d={"a":1,"b":2}
# 将字典解开 变为a=1 b=2 保证字典里面的key与函数形参一致
print(add(**d))
结果:3


posted @ 2021-10-23 09:57  王王的王  阅读(337)  评论(0)    收藏  举报