Python3连接Mysql(增删改查操作及简单的SQL指令)

3 篇文章 1 订阅

1、使用PyCharm安装pymysql

依次点击 File->settings->Project Interpreter 点击右侧绿色加号+ 输入pymysql 安装完成

2、打开数据库创建一个测试表

 

create table student(
  date varchar(50),
  information varchar(1000)
);

3、打开PyCharm

3.1 查询操作

import pymysql  #导入 pymysql  
  
#打开数据库连接  user为用户名、password为密码,根据自己的数据库修改相应的账号和密码
db= pymysql.connect(host="localhost",user="root",  
    password="123456",db="test",port=3306)  
  
# 使用cursor()方法获取操作游标  
cur = db.cursor()  
  
#1.查询操作  
# 编写sql 查询语句    
sql = "select * from studen"  
try:  
    cur.execute(sql)    #执行sql语句  
  
    results = cur.fetchall()    #获取查询的所有记录  
    print("date","information")  
    #遍历结果  
    for row in results :  
        date = row[0]  
        information = row[1]           
        print(date,information)  
except Exception as e:    #异常处理
    raise e  
finally:        #最终一定要执行的操作
    db.close()  #关闭连接  

3.2 插入、修改、删除(均可仿照3.1代码进行修改

      SQL指令见下文

4 简单的SQL指令

#创建表
create table student(
id int auto_increment primary key,
name varchar(50),
sex varchar(20),
date varchar(50),
content varchar(100)
)default charset=utf8;
 
#删除表
drop table student;
 
#查看表的结构
describe student;  #可以简写为desc student;
 
#插入数据
insert into student values(null,'aa','男','1988-10-2','......');
insert into student values(null,'bb','女','1889-03-6','......');
insert into student values(null,'cc','男','1889-08-8','......');
insert into student values(null,'dd','女','1889-12-8','......');
insert into student values(null,'ee','女','1889-09-6','......');
insert into student values(null,'ff','null','1889-09-6','......');
#查询表中的数据
select * from student;
select id,name from student;
 
#修改某一条数据
update student set sex='男' where id=4;
 
#删除数据
delete from student where id=5;
 
# and 且
select * from student where date>'1988-1-2' and date<'1988-12-1';
 
# or 或
select * from student where date<'1988-11-2' or date>'1988-12-1';
  
#between
select * from student where date between '1988-1-2' and '1988-12-1';
 
#in 查询制定集合内的数据
select * from student where id in (1,3,5);
 
#排序 asc 升序  desc 降序
select * from student order by id asc;
 
#分组查询 #聚合函数
select max(id),name,sex from student group by sex;
 
select min(date) from student;
 
select avg(id) as '求平均' from student;
 
select count(*) from student;   #统计表中总数
 
select count(sex) from student;   #统计表中性别总数  若有一条数据中sex为空的话,就不予以统计~
 
select sum(id) from student;
 
#查询第i条以后到第j条的数据(不包括第i条)
select * from student limit 2,5;  #显示3-5条数据

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值