[Python][数据库操作][学习笔记]
【摘要】 本学习笔记介绍了Python如何连接数据库并对数据库实现增删改查操作,使用最流行的MySQL数据库来演示,如果对MySQL安装不太熟悉,可以参考我的另一篇博客文章,https://bbs.huaweicloud.com/blogs/335513 1.mysql-connector 1.1.安装mysql-connectormysql-connector是MySQL官方提供的驱动器,可以用来连...
本学习笔记介绍了Python如何连接数据库并对数据库实现增删改查操作,使用最流行的MySQL数据库来演示,如果对MySQL安装不太熟悉,可以参考我的另一篇博客文章,https://bbs.huaweicloud.com/blogs/335513
1.mysql-connector
1.1.安装mysql-connector
mysql-connector是MySQL官方提供的驱动器,可以用来连接使用MySQL。使用pip命令来安装mysql-connector。
pip install mysql-connector
安装完毕后可以在任意python文件中输入以下代码验证:
import mysql.connector
如果在IDE中没有报错,则表示安装成功。
1.2.创建数据库
import mysql.connector # 导包
# 创建数据库连接
connection=mysql.connector.connect(
host="localhost",
user="username",
password="password"
)
# 创建游标对象
mycursor=connection.cursor()
# 执行sql语句
mycursor.execute("CREATE DATABASE `pythonmysql`")
1.3.创建数据表
使用CREATE TABLE
创建数据表,需要确保数据库已创建,否则会报错
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="pythonmysql"
)
mycursor = connection.cursor()
mycursor.execute("CREATE TABLE `users`"
"("
"`id` INT(11) NOT NULL AUTO_INCREMENT,"
"`email` VARCHAR(255) NOT NULL,"
"`password` VARCHAR(255) NOT NULL,"
"PRIMARY KEY(`id`)"
")ENGINE=INNODB DEFAULT CHARSET=utf8mb4;")
1.4.批量插入数据
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="pythonmysql"
)
mycursor = connection.cursor()
sql = "INSERT INTO `users`(email,password) VALUES(%s,%s)"
val = [
("123@test.com", "123",),
("456@test.com", "456"),
("789@test.com", "789")
]
# 使用executemany()方法进行批量插入,第二个参数是一个元组列表,包含了我们要插入的数据
mycursor.executemany(sql, val)
# 当对数据库进行增删改操作时,必须要进行提交
connection.commit()
# 但因成功信息
print(mycursor.rowcount, "记录插入成功") # 3 记录插入成功
1.5.查询数据
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="pythonmysql"
)
mycursor = connection.cursor()
mycursor.execute("SELECT * FROM `users`")
# fetchall() 获取所有记录
result = mycursor.fetchall()
for x in result:
print(x)
输出结果:
(1, '123@test.com', '123')
(2, '456@test.com', '456')
(3, '789@test.com', '789')
如果只读取一条数据,使用fetchone()
方法
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="pythonmysql"
)
mycursor = connection.cursor()
mycursor.execute("SELECT * FROM `users`")
# fetchone() 获取一条数据
result = mycursor.fetchone()
print(result)
输出结果:
(1, '123@test.com', '123')
1.5.1.where条件语句
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="pythonmysql"
)
mycursor = connection.cursor()
# 使用通配符%查询带有9字的内容
sql = "SELECT * FROM `users` WHERE `email` LIKE '%9%'"
mycursor.execute(sql)
result = mycursor.fetchall()
for x in result:
print(x)
输出结果:
(3, '789@test.com', '789')
使用占位符%s进行查询可以防止SQL注入攻击
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="pythonmysql"
)
mycursor = connection.cursor()
sql = "SELECT * FROM `users` WHERE email = %s"
val = ("123@test.com",)
mycursor.execute(sql, val)
result = mycursor.fetchall()
for x in result:
print(x)
输出结果:
(1, '123@test.com', '123')
1.5.2.排序
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="pythonmysql"
)
mycursor = connection.cursor()
# 默认ASC,升序排序;DESC,降序排序
sql = "SELECT * FROM `users` ORDER BY email DESC"
mycursor.execute(sql)
result = mycursor.fetchall()
for x in result:
print(x)
1.5.3.Limit
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="pythonmysql"
)
mycursor = connection.cursor()
# 用LIMIT设置查询数量为2
mycursor.execute("SELECT * FROM `users` LIMIT 2")
result = mycursor.fetchall()
for x in result:
print(x)
1.6.删除记录
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="pythonmysql"
)
mycursor = connection.cursor()
sql = "DELETE FROM `users` WHERE password='789'"
mycursor.execute(sql)
connection.commit()
print(mycursor.rowcount, " 条记录被删除") # 1 条记录被删除
1.7.更新表数据
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="pythonmysql"
)
mycursor = connection.cursor()
sql = "UPDATE `users` SET password= %s WHERE password=%s"
val = ("789", "456",)
mycursor.execute(sql, val)
connection.commit()
print(mycursor.rowcount, " 条记录被修改") # 1 条记录被修改
1.8.删除表
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="pythonmysql"
)
mycursor = connection.cursor()
sql = "DROP TABLE IF EXISTS `users`"
mycursor.execute(sql)
2.PyMySQL
2.1.PyMySQL介绍
PyMySQL是一个库,用来连接MySQL服务器。
2.2.安装PyMySQL
可以使用以下命令安装PyMySQL
pip3 install pymysql
2.3.PyMySQL连接数据库
import pymysql
# 连接数据库
connection=pymysql.connect(host="localhost",
user="root",
password="1234",
database="pymysqldb")
# 创建游标
cursor=connection.cursor()
# 执行查询
cursor.execute("SELECT VERSION()")
# 获取返回结果
reuslt=cursor.fetchone()
print("version : %s " % reuslt) # version : 8.0.27
# 关闭连接
connection.close()
2.4.数据库建表
import pymysql
# 连接数据库
connection=pymysql.connect(host="localhost",
user="root",
password="1234",
database="pymysqldb")
# 创建游标
cursor=connection.cursor()
# 执行查询,表存在则删除
cursor.execute("DROP TABLE IF EXISTS 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)
# 关闭连接
connection.close()
2.5.插入数据
import pymysql
# 连接数据库
connection=pymysql.connect(host="localhost",
user="root",
password="1234",
database="pymysqldb")
# 创建游标
cursor=connection.cursor()
# 插入语句
sql="""
INSERT INTO `EMPLOYEE`(FIRST_NAME,LAST_NAME,AGE,SEX,INCOME)
VALUES('HELLO','WORLD',20,'M',2000)
"""
try:
cursor.execute(sql)
connection.commit()
except:
connection.rollback()
# 关闭连接
connection.close()
2.6.查询数据
import pymysql
# 连接数据库
connection=pymysql.connect(host="localhost",
user="root",
password="1234",
database="pymysqldb")
# 创建游标
cursor=connection.cursor()
# 查询income字段大于1000
sql="SELECT * FROM EMPLOYEE WHERE INCOME > %s"%(1000)
try:
cursor.execute(sql)
result=cursor.fetchall()
for row in result:
fname=row[0]
lname=row[1]
age=row[2]
sex=row[3]
income=row[4]
print("fname=%s,lname=%s,age=%s,sex=%s,income=%s"%(fname,lname,age,sex,income))
except:
print("数据不匹配")
# 关闭连接
connection.close()
输出结果:
fname=HELLO,lname=WORLD,age=20,sex=M,income=2000.0
fname=AB,lname=CD,age=18,sex=F,income=3000.0
fname=PY,lname=THON,age=30,sex=M,income=2500.0
2.7.更新数据
import pymysql
# 连接数据库
connection=pymysql.connect(host="localhost",
user="root",
password="1234",
database="pymysqldb")
# 创建游标
cursor=connection.cursor()
# SQL更新
sql="UPDATE EMPLOYEE SET AGE=AGE+1 WHERE SEX='%c'"%('M')
try:
cursor.execute(sql)
connection.commit()
except:
connection.rollback()
# 关闭连接
connection.close()
2.8.删除数据
import pymysql
# 连接数据库
connection=pymysql.connect(host="localhost",
user="root",
password="1234",
database="pymysqldb")
# 创建游标
cursor=connection.cursor()
# SQL删除
sql="DELETE FROM EMPLOYEE WHERE SEX='%c'"%('M')
try:
cursor.execute(sql)
connection.commit()
except:
connection.rollback()
# 关闭连接
connection.close()
2.9.事务
事务机制可以保证数据一致性。具有4个属性:原子性、一致性、隔离性、持久性。通常称为ACID属性。
- 原子性(atomicity),一个事务是一个不可分割的工作单位,事务中包括的诸操作要么都做,要么都不做。
- 一致性(consistency)。事务必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的。
- 隔离性(isolation)。一个事务的执行不能被其他事务干扰。即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。
- 持久性(durability)。持续性也称永久性(permanence),指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响。
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)