Python操作MySQL:
- 创建数据表
- 插入数据
- 查询数据
- 修改数据
- 删除数据
首先确保已创建数据库,python安装好pymysql库
pip install pymysql
1、创建数据表
import pymysql # 导入 pymysql
#打开数据库连接
db = pymysql.connect(host="localhost", user="root",
password="123456", db="t1", port=3306)
# 使用cursor()方法获取操作游标
cur = db.cursor()
#创建数据表语句
create_table = '''create table if not exists test(
id int unsigned auto_increment,
name varchar(10) not null,
age int not null,
salary int,
primary key (id)
)'''
# drop_table = "drop table test" #删除数据表语句
cur.execute(create_table)
db.close() #关闭数据库
2、插入数据
import pymysql # 导入 pymysql
#打开数据库连接
db = pymysql.connect(host="localhost", user="root",
password="123456", db="t1", port=3306)
# 使用cursor()方法获取操作游标
cur = db.cursor()
#1.查询操作
sql_insert1 = "insert into test(name,age,salary) values('张三',32,20000)" # 插入语句1
# sql_insert2 = "insert into test(name,age,salary) values(%s,%s,%s)" # 插入语句2
# value = ['李四', 30, 15000]
try:
cur.execute(sql_insert1) # 执行插入语句1
# cur.execute(sql_insert2,value) # 执行插入语句2
db.commit() #提交到数据库
except:
db.rollback() #发生错误时回滚
db.close() # 关闭数据库
3、 查询数据
import pymysql
#打开数据库连接
db = pymysql.connect(host="localhost", user="root",
password="123456", db="t1", port=3306)
# 使用cursor()方法获取操作游标
cur = db.cursor()
#1.查询操作
sql_query = "select * from test" # 查询语句
cur.execute(sql_query) # 执行查询语句
# result = cur.fetchall() #获取全部查询结果
result = cur.fetchone() #获取一条查询结果
print(result)
db.close() # 关闭数据库
4、修改数据
import pymysql # 导入 pymysql
#打开数据库连接
db = pymysql.connect(host="localhost", user="root",
password="123456", db="t1", port=3306)
# 使用cursor()方法获取操作游标
cur = db.cursor()
#1.update操作
sql_update = "update test set age = age+10 where name='张三'" # 更新语句1
try:
cur.execute(sql_update) # 执行update语句1
db.commit() #提交到数据库
except:
db.rollback() #发生错误时回滚
db.close() # 关闭数据库
5、删除数据
import pymysql # 导入 pymysql
#打开数据库连接
db = pymysql.connect(host="localhost", user="root",
password="123456", db="t1", port=3306)
# 使用cursor()方法获取操作游标
cur = db.cursor()
#1.delete操作
sql_delete = "delete from test where id=2" # delete语句1
try:
cur.execute(sql_delete) # 执行delete语句1
db.commit() #提交到数据库
except:
db.rollback() #发生错误时回滚
db.close() # 关闭数据库
相关操作后数据表内容如下,直接在vscode显示: