Python operation MySQL
Install pymysql third-party package
sudo pip install pymysql
There are five processes to operate the database
建立和数据库服务器的连接
通过连接获取游标
使用游标堆数据库进行操作
关闭游标资源
断开连接
import pymysql
# 1.建立与服务器的连接,获取连接对象
coon = pymysql.connect(host='127.0.0.0', port=3306, user='root', password='mysql', database='school', charset='utf8')
# 2.通过连接获取游标
cur = coon.cursor()
# 3.利用游标操作数据库
sql = "select * from students"
no = cur.execute(sql)
print(no)
# 3.1 获取结果
print(cur.fetchall())
# 3.2发生错误时,回滚
coon.rollback()
# 4.关闭游标
cur.close()
# 5.关闭连接
coon.close()
If you forget what information needs to be filled in to connect to the database, you can view the source code
Various database operations
Get all data at once
cur.fetchall() #fetch 获取 all 全部
This operation will get all the data of the entire table and display it in the form of tuples,
一次只可获取一次
Example result:
((22,xiaoming,man),(23,xiaohong,woman),(24,xiaokeai,man))
Fetch data one row at a time
cur.fetchone()
一次获取一行数据如果写两遍,则获取第一行和第二行数据
CRUD operation
Addition, deletion and modification operations need to modify the sql statement, and then submit it (not submitted by default)
sql = "update student set age = 4 where id = 3"
sql = "insert into student (name,age) VALUES ('小明',12)"
sql = "delete from student where id = 2"
cur.execute(sql)
conn.commit()