数据库交互pymysql模块
一、python连接数据库
基本格式:
import pymysql
db = pymysql.connect(host='127.0.0.1', # 数据库IP
user='root', # 用户
password='123', # 密码
database='staff') # 数据库
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行SQL语句
cursor.execute('select version()')
# 使用 fetchone() 方法获取单条数据
data = cursor.fetchone()
# 打印获取结果
print(data)
db.close() # 关闭数据库连接
创建表操作:
import pymysql
# 打开数据库连接
db = pymysql.connect(host='127.0.0.1',
user='root',
password='123',
database='staff')
cursor = db.cursor() # 创建一个游标对象
# 使用execute() 方法执行SQL,如果 employee 表存在则删除
cursor.execute('DROP TABLE IF EXISTS employee')
# 使用预处理语句创建 employee 表
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
# 运行预处理语句
cursor.execute(sql)
db.close() # 关闭数据库连接
数据插入操作:
import pymysql
db = pymysql.connect(host='127.0.0.1',
user='root',
password='123',
database='staff')
cursor = db.cursor()
# SQL 插入语句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
cursor.execute(sql) # 执行SQL语句
db.commit() # 提交到数据库执行
except:
db.rollback() # 如果发生错误则回滚
db.close()
数据查询操作:
python查询MySQL使用 fetchone( ) 方法获取单条数据,使用 fetchall( ) 方法获取多条数据
fetchone( ):该方法获取下一个查询结果集,结果集是一个对象
fetchall( ):接收全部的返回结果行
rowcount:这是一个只读属性,并返回执行 execute( ) 方法后影响的行数
# fetchone方法:
import pymysql
db = pymysql.connect(host='127.0.0.1',
user='root',
password='123',
database='staff')
cursor = db.cursor()
sql = 'select * from employee'
cursor.execute(sql)
data = cursor.fetchone()
print(data)
db.close()
# 输出
('Mac', 'Mohan', 20, 'M', 2000.0)
# ------------------------------------------------------------------------------
# fetchall方法:
import pymysql
db = pymysql.connect(host='127.0.0.1',
user='root',
password='123',
database='staff')
cursor = db.cursor()
sql = 'select * from employee'
cursor.execute(sql)
data = cursor.fetchall()
print(data)
db.close()
# 输出
(('Mac', 'Mohan', 20, 'M', 2000.0), ('yang', 'xiao', 18, 'M', 3000.0), ('hong', 'xiao', 18, 'F', 3000.0))
# --------------------------------------------------------------------------------
# rowcount方法
import pymysql
db = pymysql.connect(host='127.0.0.1',
user='root',
password='123',
database='staff')
cursor = db.cursor()
sql = 'select * from employee'
cursor.execute(sql)
data = cursor.rowcount
print(data)
db.close()
# 输出
3
数据更新操作:
import pymysql
db = pymysql.connect(host='127.0.0.1',
user='root',
password='123',
database='staff')
cursor = db.cursor()
# 改之前
cursor.execute("select * from employee where sex = 'F'")
data1 = cursor.fetchone()
print('改之前:', data1)
# sql 更新语句
sql = "update employee set age = age+1 where sex = 'F'"
try:
cursor.execute(sql) # 执行SQL语句
db.commit() # 提交到数据库执行
except:
db.rollback() # 发生错误时回滚
# 改了之后
cursor.execute("select * from employee where sex = 'F'")
data2 = cursor.fetchone()
print('改之后:', data2)
db.close()
# 输出
改之前: ('hong', 'xiao', 22, 'F', 3000.0)
改之后: ('hong', 'xiao', 23, 'F', 3000.0)
数据删除操作:
import pymysql
db = pymysql.connect(host='127.0.0.1',
user='root',
password='123',
database='staff')
cursor = db.cursor()
# 删除语句
sql = 'delete from employee where age > 20'
try:
cursor.execute(sql) # 执行SQL语句
db.commit() # 提交修改
except:
db.rollback()
cursor.execute("select * from employee")
data = cursor.fetchall()
print(data)
db.close()
# 输出
(('Mac', 'Mohan', 20, 'M', 2000.0), ('yang', 'xiao', 18, 'M', 3000.0))
二、数据备份
数据库的逻辑备份:
备份数据 在cmd命令行直接执行
# 语法:
# mysqldump -h 服务器 -u用户名 -p密码 数据库名 > 备份文件.sql
# 示例:
# 单库备份
mysqldump -uroot -p123 db1 > db1.sql
mysqldump -uroot -p123 db1 table1 table2 > db1-table1-table2.sql
# 多库备份
mysqldump -uroot -p123 --databases db1 db2 mysql db3 > db1_db2_mysql_db3.sql
# 备份所有库
mysqldump -uroot -p123 --all-databases > all.sql
数据恢复:
方法一:cmd命令行直接执行
方法二:恢复数据 在mysql中执行命令
# 方法一:
[root@egon backup]# mysql -uroot -p123 < /backup/all.sql
# 方法二:
mysql> use db1;
mysql> SET SQL_LOG_BIN=0; #关闭二进制日志,只对当前session生效
mysql> source /root/db1.sql
三、事物和锁
为了避免同一行数据,同时被两个或多个用户的SQL语句进行算数运算的操作,尽管在计算算到写入的过程很短,但还是有数据不安全的情况,所以要加一把锁,同一时间只能有同一个用户对同一行数据进行操作。
begin; # 开启事务
select * from emp where id = 1 for update; # 查询id值,for update添加行锁;
update emp set salary=10000 where id = 1; # 完成更新
commit; # 提交事务
本文来自博客园,作者:Mr-Yang`,转载请注明原文链接:https://www.cnblogs.com/XiaoYang-sir/p/14841397.html