python连接数据库插入数据

python连接数据库插入数据

在数据库创建表并插入测试数据

drop database if exists hrs;
create database hrs default charset utf8mb4;

use hrs;

create table tb_dept
(
dno int not null comment '编号',
dname varchar(10) not null comment '名称',
dloc varchar(20) not null comment '所在地',
primary key (dno)
);

insert into tb_dept values 
    (10, '会计部', '北京'),
    (20, '研发部', '成都'),
    (30, '销售部', '重庆'),
    (40, '运维部', '深圳');

create table tb_emp
(
eno int not null comment '员工编号',
ename varchar(20) not null comment '员工姓名',
job varchar(20) not null comment '员工职位',
mgr int comment '主管编号',
sal int not null comment '员工月薪',
comm int comment '每月补贴',
dno int comment '所在部门编号',
primary key (eno)
);

-- alter table tb_emp add constraint pk_emp_eno primary key (eno);
-- alter table tb_emp add constraint uk_emp_ename unique (ename);
-- alter table tb_emp add constraint fk_emp_mgr foreign key (mgr) references tb_emp (eno);
-- alter table tb_emp add constraint fk_emp_dno foreign key (dno) references tb_dept (dno);

insert into tb_emp values 
    (7800, '张三丰', '总裁', null, 9000, 1200, 20),
    (2056, '乔峰', '分析师', 7800, 5000, 1500, 20),
    (3088, '李莫愁', '设计师', 2056, 3500, 800, 20),
    (3211, '张无忌', '程序员', 2056, 3200, null, 20),
    (3233, '丘处机', '程序员', 2056, 3400, null, 20),
    (3251, '张翠山', '程序员', 2056, 4000, null, 20),
    (5566, '宋远桥', '会计师', 7800, 4000, 1000, 10),
    (5234, '郭靖', '出纳', 5566, 2000, null, 10),
    (3344, '黄蓉', '销售主管', 7800, 3000, 800, 30),
    (1359, '胡一刀', '销售员', 3344, 1800, 200, 30),
    (4466, '苗人凤', '销售员', 3344, 2500, null, 30),
    (3244, '欧阳锋', '程序员', 3088, 3200, null, 20),
    (3577, '杨过', '会计', 5566, 2200, null, 10),
    (3588, '朱九真', '会计', 5566, 2500, null, 10);
    
-- mysql中的简单查询语句
use hrs;
-- 查询月薪最高的员工姓名和月薪
-- select ename, sal from tb_emp order by sal desc limit 1;
select ename, sal from tb_emp where sal=(select max(sal) from tb_emp);
select ename, sal from tb_emp t1 where not exists (select 'x' from tb_emp t2 where t2.sal>t1.sal);
select ename, sal from tb_emp t1 where (select count(*) from tb_emp t2 where t2.sal>t1.sal)=0;
select ename, sal from tb_emp t1 where (select count(*) from tb_emp t2 where t2.sal>t1.sal)<1;
-- 查询员工的姓名和年薪((月薪+补贴)*13)
select ename, (ifnull(sal, 0) + ifnull(comm, 0))*13 as yearly_salary from tb_emp order by yearly_salary desc;
-- 查询有员工的部门的编号和人数

select dno as 编号, count(eno) as 人数 from tb_emp group by dno;

-- 查询所有部门的名称和人数
select dname as 名称, ifnull(人数, 0) from tb_dept t1 left join (select dno, count(eno) as 人数 from tb_emp group by dno) t2 on t1.dno=t2.dno;
-- 查询月薪最高的员工(Boss除外)的姓名和月薪
-- select ename, sal from tb_emp where job<>'总裁' order by sal desc limit 1;
select ename, sal from tb_emp where sal=(select max(sal) from tb_emp where job<>'总裁');
-- 查询月薪超过平均月薪的员工的姓名和月薪

select ename, sal from tb_emp where sal>(select avg(sal) from tb_emp);

-- 查询月薪超过其所在部门平均月薪的员工的姓名、部门编号和月薪
select ename, t1.dno, sal from tb_emp t1 inner join 
(select dno, avg(sal) as avg_sal from tb_emp group by dno) t2 on t1.dno=t2.dno and sal>avg_sal order by t1.dno;

-- 查询部门中月薪最高的人姓名、月薪和所在部门名称
select ename, sal, dname from tb_emp, tb_dept,
(select dno, max(sal) as 最高薪水 from tb_emp group by dno) t3
where tb_emp.dno=tb_dept.dno and tb_emp.dno=t3.dno and sal=最高薪水;

select ename, sal, dname from tb_emp inner join tb_dept inner join
(select dno, max(sal) as 最高薪水 from tb_emp group by dno) t3
on tb_emp.dno=tb_dept.dno and tb_emp.dno=t3.dno and sal=最高薪水;

-- 查询月薪最高的员工姓名和月薪
select ename, sal from tb_emp t1 where (select count(*) from tb_emp t2 where t2.sal>t1.sal)=0;
select ename, sal from tb_emp t1 where (select count(*) from tb_emp t2 where t2.sal>t1.sal)<1;

-- 查询每个部门月薪的前两名的员工姓名,月薪和部门编号
select ename, sal, dno from tb_emp t1 where (
select count(*) from tb_emp t2 where t1.dno=t2.dno and t2.sal>t1.sal)<2 
order by dno asc, sal desc;

-- 使用窗口函数 查询每个部门月薪的前两名的员工姓名,月薪和部门编号
select ename, sal, dno from 
(select 
rank() over (partition by dno order by sal desc) as rank_num,
ename, sal, dno
from tb_emp) temp where rank_num<=2;

-- 查询主管的姓名和职位
select ename, job from tb_emp where eno in
(select distinct mgr from tb_emp where mgr is not null);

select ename, job from tb_emp where eno=any
(select distinct mgr from tb_emp where mgr is not null);

select ename, job from tb_emp t1 where exists
(select 'x' from tb_emp t2 where t1.eno=t2.mgr);
-- 查询月薪排名4~6名的员工排名、姓名和月薪
select ename, sal from tb_emp order by sal desc limit 3 offset 3;
use hrs;
select ename, sal,ranking from(select ename, sal,
row_number() over (order by sal desc ) as rownum,
rank() over (order by sal desc) as ranking,
dense_rank() over (order by sal desc) as den_ranking 
from tb_emp) tb_temp where ranking between 4 and 6;

通过python连接数据库插入数据

import pymysql

no = int(input("请输入部门编号:"))
name = input("请输入部门名称:")
loc = input("请输入部门所在地:")

# 第一步:创建连接
# 在默认情况下创建连接,相当于开启了一个事物环境
# 事物:把若干个(增删改)操作视为一个不可分割的原子性操作,要么全都成功,要么全都失败。
conn = pymysql.connect(
    host="主机名",
    database="hrs",
    user="用户名",
    password="密码",
    port=3306,
    charset='utf8'
)

# print(conn)

try:
    # 第二步:获取游标对象
    with conn.cursor() as cursor:
        # 第三步:通过游标对象向数据库发出SQL并获取执行结果
        # 不允许任何形式的格式化字符串进行数据操作
        affected_rows = cursor.execute(
            'insert into tb_dept values (%s, %s, %s)',
            (no, name, loc)
        )
        if affected_rows == 1:
            print('添加部门成功!')

    # 第四步:手动提交
    conn.commit()
except pymysql.MySQLError:
    # 手动回滚
    conn.rollback()
# 第五步:关闭连接
finally:
    conn.close()
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Python连接MySQL数据库插入数据的步骤如下: 1. 安装MySQL驱动程序 在Python中连接MySQL数据库需要使用MySQL驱动程序,可以使用pip命令安装MySQL驱动程序,命令如下: ``` pip install mysql-connector-python ``` 2. 连接MySQL数据库 使用MySQL驱动程序连接MySQL数据库,需要提供MySQL数据库的主机名、用户名、密码、数据库名称等信息。连接MySQL数据库的代码如下: ``` import mysql.connector # 连接MySQL数据库 mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="yourdatabase" ) ``` 3. 插入数据 连接MySQL数据库后,可以使用SQL语句向MySQL数据库插入数据插入数据的代码如下: ``` import mysql.connector # 连接MySQL数据库 mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="yourdatabase" ) # 获取游标 mycursor = mydb.cursor() # 插入数据 sql = "INSERT INTO customers (name, address) VALUES (%s, %s)" val = ("John", "Highway 21") mycursor.execute(sql, val) # 提交事务 mydb.commit() # 输出插入数据的主键ID print("插入数据的主键ID:", mycursor.lastrowid) ``` 以上代码中,使用INSERT INTO语句向customers表中插入数据插入数据为name和address字段的值。使用execute()方法执行SQL语句,使用commit()方法提交事务,使用lastrowid属性获取插入数据的主键ID。 希望以上回答能够帮助到您。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

azured_xu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值