Python + MySQL从入门到精通(四):数据表操作

该文介绍了Python连接MySQL的基础,包括安装、配置、数据库操作如连接、创建、删除表,以及数据类型的使用,如整数、小数、字符型。还详细讲解了如何创建带主键和自增属性的表,并展示了使用Python的pymysql模块执行SQL语句进行数据库操作的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前期工作

Python + MySQL从入门到精通(一):安装MySQL

Python + MySQL从入门到精通(二):配置账户密码
Python + MySQL从入门到精通(三):数据库的连接、创建、删除操作

MySQL中常见的数据类型

  • 整数:int
  • 小数:decimal
    • 较少用:float,double
  • 字符型:
    • char:固定长度
    • varchar:可变长度
  • 其他类型:详见官网https://dev.mysql.com/doc/refman/5.7/en/data-types.html

内置客户端操作

进入数据库:

use 数据库名称;

查看当前数据库中的所有表:

show tables;

查看表结构:

desc 表名;

创建表

create table 表名(
	列名 类型,
    列名 类型,
    列名 类型,
)default charset=utf8;

举例:

create table tb1(
	id int,
    name varchar(16)
)default charset=utf8;

–表示sql语法中的注释

not null:不为空

create table tb2(
	id int,
    name varchar(16) not null,--不允许为空
    email varchar(16) null,--允许为空(默认)
    age int default 3--插入数据时,如果不给age列设置值,默认值为3
)default charset=utf8;

主键

create table tb3(
	id int primary key,  --主键(不允许为空,不能重复)
    name varchar(16) not null,
    email varchar(16) null,
    age int default 3    
)default charset=utf8;

主键一般用于表示当前这条数据的ID编号(类似于人的身份证),需要我们自己来维护一个不重复的值,比较繁琐。所以,在数据库中一般会将主键和自增结合

create table tb4(
	id int not null auto_increment primary key,  --不允许为空 & 主键 & 自增
    name varchar(16) not null,  --不允许为空
    email varchar(32) null,  --允许为空(默认)
    age int default 3 --插入数据时,如果不给age列设置值,默认值:3
) default charset=utf8;

删除表 :

drop table 表名;

清空表

delete from 表名;
truncate table 表名;  --速度快,无法回滚或撤销

修改表

​ 添加列

alter table 表名 add 列名 类型;
alter table 表名 add 列名 类型 DEFAULT 默认值;
alter table 表名 add 列名 类型 not null default 默认值;
alter table 表名 add 列名 类型 not null primary key auto_increment;

​ 删除列

alter table 表名 drop column 列名;

​ 修改列类型

alter table 表名 modify column 列名 类型;

​ 修改列类型+名称

alter table 表名 change 原列名 新列名 新类型
alter table tb change id id int not null;
alter table tb change id id int not null default 5;
alter table tb change id id int not null primary key auto_increment;
alter table tb change id id int; --允许为空,删除默认值、删除自增

​ 修改列 默认值

alter table 表名 alter 列名 set default 1000;

​ 删除列 默认值

alter table 表名 alter 列名 drop default

​ 添加主键

alter table 表名 add primary key(列名)

​ 删除主键

alter table 表名 drop primary key;

Python代码操作

使用上述SQL语句进行操作
举例:创建表

import pymysql

#使用数据库db1
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root123', charset="utf8", db="db1")
cursor = conn.cursor()

#创建数据表test1_tb
sql="create table test1_tb(id int,name varchar(16))default charset=utf8;"
cursor.execute(sql)
conn.commit()

sql="show tables"
cursor.execute(sql)
values = cursor.fetchall()
print(values)

#关闭数据库连接
cursor.close()
conn.close()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值