pymysql模块的使用
下载
pip3 install pymysql
使用
连接MySQL
import pymysql
conn = pymysql.connect(host='192.168.10.159',user='root',password='root',database='123',port=3306,charset='utf8')
# 获取链接的对象 相当于 获取socket对象一样,本质mysql客户端也是socket的数据通信
cursor = conn.cursor()
# 获取游标,相当于mysql的客户端的接收数据的缓存空间对象。
# 默认使用mysql客户端 发送show databases; 那么返回的数据直接打印到屏幕上。
cursor.execute('show databases;')
# pymysql 的excute 执行后,接收到数据是存在到对象的存储内。
cursor.fetchall()
result = cursor.fetchall()
print(result)
# 把数据反解成python所识别的元组类型。
(('123',), ('information_schema',), ('mysql',), ('performance_schema',), ('sys',))
fetchall() 获取全部的数据
fetone() 获取第一行的数据
fetchmany()括号内可以指定获取几个结果集,展示的形式是列表套字典
1.创建库和创建表的操作都是执行sql语句execute, cursor.execute(),创建库和创建表,不需要提交commit,
2.在对于数据表的操作中,凡是涉及到修改数据的都必须使用cursor.commit,pysql链接到服务端后自动开启了事务,开启事务后,自动提交策略默认是 false,所以要commit,
如果在conn创建链接后,执行autocommit=1,打开自动提交,后续就不需要执行commit,但是事务的回滚rollback可能也就无法生效
比如就是银行转账时,我的钱转出去了,钱少了,此时发生故障,收款人没有收到的场景。
表操作
查询操作
conn = pymysql.connect(host='121.36.135.84',user='root',password='root',database='user',port=59782,charset='utf8')
cursor = conn.cursor()
cursor.execute('select id,user,password,ctime from user.stone1;')
results = cursor.fetchone()
print(results)
变量
格式化字符串 切记,%s 不需要加单双引号,不需要考虑sql注入的问题。
sql = "select id,name from school.student where id=%s"%(1)
sql = "select id,name from school.student where id={}".format('1')
num =1
sql = "select id,name from school.student where id={id}".format(id=num)
num = 1
sql = f"select id,name from school.student where id={num}"
更改表数据 使用
1.使用提交
sql = "insert into school.student(id,name) values (10,'dang');"
conn.commit()
2.自增字段,不写values
mysql> select * from zuoye;
+----+------+----------+--------+------------+--------+
| id | name | password | gender | email | amount |
+----+------+----------+--------+------------+--------+
| 1 | hj | ghjh | 男 | hj | 100.20 |
| 2 | 123 | 123 | 男 | 123@qq.com | 100.00 |
| 3 | 123 | 123 | 男 | 123@qq.com | 100.00 |
+----+------+----------+--------+------------+--------+
"insert into zuoye(name,password,gender,email,amount)values ('123','123','男','123@qq.com',100);"
3、 字符串 和 数字 的变量
字符串变量加引号
数字变量不加引号
"insert into zuoye(name,password,gender,email,amount,ctime)values ('123','123','男','123@qq.com',100,'%s');"%(date_res)
"insert into zuoye(name,password,gender,email,amount,ctime)values ('123','123','男','123@qq.com',100,'{}');".format(date_res)
"insert into zuoye(name,password,gender,email,amount,ctime)values ('123','123','男','123@qq.com',100,'{time}');".format(time=date_res)
4 多行插入
sql = "insert into zuoye(name,password,gender,email,amount,ctime)values" \
" ('123','123','男','123@qq.com',100,'{d1}')," \
"('123','123','男','123@qq.com',200,'{d1}');".format(d1 = date_res)
5、整型 相加
update school.`zuoye` set amount= amount+1000 ;
execute执行
在excute 中 拼接SQL语句 不能加引号 ,会自动加引号,一般使用sql放入excute内使用。不要自己拼接字符串!!
cursor.execute("select * from users where name=%s and password=%s", [user, pwd])
cursor.execute("select * from users where name=%(n1)s and password=%(n2)s", {"n1": user, 'n2': pwd})