上一篇博客准备数据集,这一篇博客主要是利用sql语句查询数据和利用Python操作MySQL。
sql基本操作
sql的增删改查
select * from 表名 where 条件
delete from 表名 where 条件
insert into 表名 (字段名) values (字段值)
update 表名 set xxx=xxx where 条件
sql语句书写
select xxx
from xxx,xxx
where xxx
group by xxx
order by xxx
limit xxx \G;
然后就是根据查询需求按照上面书写规范进行编写查询语句
Python操作MySQL
首先下载pymysqsl,再命令行窗口输入pip install pymysql
连接MySQL数据库
import pymysql
#打开数据库连接
conn = pymysql.connect(host="localhost", user="root", password="yanzhiguo", port=3306, db="learnmybatis")
#执行命令 创建数据表aaa
# sql = 'create table aaa (id int ,name varchar(32))'
# cursor.execute(sql)
导入pymysql,然后调用connect即可完成连接数据库,
host:本地连接 localhost
user:用户名
password:密码
port:端口号
db:数据库
增加记录
import pymysql
#打开数据库连接
conn = pymysql.connect(host="localhost", user="root", password="yanzhiguo", port=3306, db="learnmybatis")
#创建一个游标
cursor = conn.cursor()
#使用游标执行命令
#可以直接cursor.execute("select * from aaa")
#或者sql = 'selcet * from AAA'
#cursor.execute(sql)这两种方式
#插入数据的两种方式
sql_insert1 = "insert into aaa (id,name) values (1,'yzg')"
id = 123
name = 'zhi'
#重点注意插入语句的形式
sql_insert2 = "insert into aaa (id,name) values('%s','%s')"%((id,name))
try:
#执行插入语句
cursor.execute(sql_insert1)
cursor.execute(sql_insert2)
#提交到数据库执
conn.commit()
except:
#如果发生错误 进行数据库回滚
conn.rollback()
查询记录
#Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。
sql_select = 'select * from aaa'
#查询一个结果
cursor.execute(sql_select)
result = cursor.fetchone()
print(result)
#查询多个结果
cursor.execute(sql_select)
result = cursor.fetchall()
for row in result:
print(str(row[0])+" "+row[1])
修改记录
id = 1
sql_update = "update aaa set name = 'yanzhiguo' where id = '%s'"%(id)
try:
cursor.execute(sql_update)
conn.commit()
except:
conn.rollback()
删除记录
id = 1
sql_delete = "delete from aaa where id = '%s' "%(id)
try:
cursor.execute(sql_delete)
conn.commit()
except:
conn.rollback()
#关闭数据连接
conn.close()
执行事务
try:
# 执行SQL语句
cursor.execute(sql)
# 向数据库提交
db.commit()
except:
# 发生错误时回滚
db.rollback()
这些知识都是以前学过的,但是,好久没有使用,感觉很陌生。