当前位置:网站首页>Djiango第二次培训
Djiango第二次培训
2022-08-03 05:10:00 【曲水流觞683】
一、SQL语句
1.1 SQL简介
SQL 是一种标准化的语言,它允许你在数据库上执行操作,如创建数据库、表等等,查询内容,更新内容,并删除条目等操作。Create, Read, Update, and Delete 通常称为CRUD操作。
1.2 SQL语句分类
DDL(Data Definition Language):数据定义语言,用来定义数据库对象:库、表、列等。
DML(Data Manipulation Language):数据操作语言,用来定义数据库记录(数据)。
DCL(Data Control Language):数据控制语言,用来定义访问权限和安全级别。
DQL(Data Query Language):数据查询语言,用来查询记录(数据)。
1.3常用到的SQL语句
Show databases
Show tables
Insert into 表名() values()
Update 表名 set 字段=值 where ...
Delete from 表名 where ...
Select * from 表名 where 条件 order by ...
Desc/asc limit ...Group by ... Having ...
create database test1222; #创建数据库
show databases; #显示当前所有的数据库
alter database test1222 character set utf8; #修改当前数据库的字符编码为utf8
drop database if exists test122202; #删除数据库test122202,如果该数据库存在的话
# ---------------------------------
create table if not exists student(
id int primary key auto_increment, #主键约束,自动增长约束
`name` varchar(30) not null unique, #非空约束,唯一约束
age int,
address varchar(40),
heigh double(5,2), #这是浮点数类型,最多5位,其中必须有两位小数,即最大值为999.99
weight decimal(5,2), #这是精确数值类型,我们定义为:能够存储具有五位数和两位小数的任何值,存储范围为-999.99至999.99。
jianjie text, #这是大文本字符串类型,适合存储比较大的文本数据
photo blob, #这是二进制数据类型,适合存储图片、音频、视频等
birthday date, #日期类型,格式为:yyyy-mm-dd
ruxuetime datetime #日期时间类型 yyyy-mm-dd hh:mm:ss
)charset=utf8;
# ---------------------------------
drop table table_name; #删除某个表;
show tables; #显示当前的库中所有的数据表;
desc student; #查看数据表student中的所有字段;
alter table student add company varchar(50); #为student表增加一个字段;
#一次添加多条数据:
insert into student(id,`name`,age,address) values (4,'曹操',27,'北京海淀'),(5,'周瑜',28,'北京朝阳'),(6,'赵云',30,'北京大兴');
update student set age=24,address="河北保定" where id=1; #更新某条数据
update student set age=age+5; #将所有的年龄都加5岁;
# ---------------------------------
delete from student where `name`="zhangsan"; #删除表中的某个字段;
#对比:
drop table table_name; #删除某个表;
1.4 SELECT语句书写顺序
语法:
select 列名 from 表名 【where --> group by-->having--> order by-->limit】
select selection_list /*要查询的列名称*/
from table_list /*要查询的表名称*/
where condition /*行条件*/
group by grouping_columns /*对结果分组*/
having condition /*分组后的行条件*/
order by sorting_columns /*对结果排序*/
limit offset_start, row_count /*结果限定*/
二、Python连接MySQL数据库
1、 连接数据库
1、下载安装pymyql库
pip3 install pymysql
2、导入库
import pymysql
3、连接数据库,最好用try except捕获异常
DBHOST = 'localhost'
DBUSER = 'root'
DBPASS = 'root'
DBNAME = 'dbtest'
try:
db = pymysql.connect(host=DBHOST,user=DBUSER, password=DBPASS, database=DBNAME)
print('数据库连接成功!')
except pymysql.Error as e:
print('数据库连接失败'+str(e))
2、创建一张新表
1、声明一个游标
cur = db.cursor()
2、创建表之前先检查是否存在,如果存在则删除
cur.execute('DROP TABLE IF EXISTS Student')
3、编辑sql语句
sqlQuery = "CREATE TABLE Student(Name CHAR(20) NOT NULL ,Email CHAR(20),Age int )"
cur.execute(sqlQuery)
3、向表中插入一条数据
1、编辑sql语句
sqlQuery=" INSERT INTO Student (Name, Email, Age) VALUE (%s,%s,%s) "
2、编辑准备插入的值
value=('Mike','[email protected]',20)
3、执行sql语句
try:
cur.execute(sqlQuery,value)
db.commit()
print('数据插入成功!')
except pymysql.Error as e:
print("数据插入失败:"+e )
db.rollback()
4、查询表中的数据
1、编辑sql语句
sqlQuery = "SELECT * FROM Student"
2、使用fetchall()方法接收全部的返回结果行
try:
cur.execute(sqlQuery)
results=cur.fetchall()
for row in results:
name=row[0]
email=row[1]
age=row[2]
print('Name:%s,Email:%s,Age:%s'%(name,email,age))
except pymysql.Error as e:
print("数据查询失败:"+str(e))
5、更新表中的数据
1、编辑sql语句
sqlQuery = "UPDATE Student SET Name= %s WHERE Name=%s"
2、编辑更新的信息
value = ('John', 'updated name')
3、提交修改
try:
cur.execute(sqlQuery, value)
db.commit()
print('数据更新成功!')
except pymysql.Error as e:
print("数据更新失败:"+str(e))
# 发生错误时回滚
db.rollback()
6、删除表中的数据
1、编辑sql语句
sqlQuery = "DELETE FROM Student where Name=%s"
2、编辑更新的信息
value = ('John')
3、提交修改
try:
cur.execute(sqlQuery, value)
db.commit()
print('Date Deleted Successfully')
except pymysql.Error as e:
print("数据删除失败:"+str(e))
# 发生错误时回滚
db.rollback()
7、删除一张表
1、编辑sql语句
sqlQuery='DROP TABLE IF EXISTS Student'
2、提交修改
cur.execute(sqlQuery)
print('表删除成功!')
三、 Django连接数据库
(8条消息) Python3用Django连接Mysql-很详细的亲测过程(Mac或者Windows)_一心精通Java的靓仔程序员的博客-CSDN博客_django连接mysql
边栏推荐
- Unity2D horizontal board game tutorial 6 - enemy AI and attack animation
- 2022/08/02 Study Notes (day22) Multithreading
- High availability, two locations and three centers
- 【 Harmony OS 】 【 ano UI 】 lightweight data storage
- MySql数据库
- Alienware上线首个数字时装AR试穿体验
- Power button 561. An array of split
- 接口测试框架实战(一) | Requests 与接口请求构造
- 1059 C语言竞赛 (20 分)(C语言)
- vim命令
猜你喜欢

Common fluorescent dyes to modify a variety of groups and its excitation and emission wavelength data in the data

【Harmony OS】【ARK UI】ets use startAbility or startAbilityForResult to invoke Ability

MCM box model modeling method and source analysis of atmospheric O3

Unity2D horizontal board game tutorial 6 - enemy AI and attack animation
高效率科研神器——小软件、大能量

高可用 两地三中心

Redis6学习笔记

接口测试框架实战(四)| 搞定 Schema 断言

MySql数据库

【HMS core】【Ads Kit】Huawei Advertising——Overseas applications are tested in China. Official advertisements cannot be displayed
随机推荐
js garbage collection mechanism
阿里云对象存储oss私有桶生成链接
typescript47-函数之间的类型兼容性
建造者模式(Builder Pattern)
【Harmony OS】【FAQ】Hongmeng Questions Collection 1
获取Ip工具类
ss-4.2 多个eureka集群案例
Interface Test Framework Practice (4) | Get Schema Assertion
Apache DolphinScheduler版本2.0.5分布式集群的安装
GIS数据漫谈(六)— 投影坐标系统
斐讯K2路由编译Padavan华硕固件和心得
typescript40-class类的保护修饰符
Practical application of WebSocket
Interface testing framework combat (3) | JSON request and response assertion
c语言结构体中的冒泡排序
Interface test framework combat (1) | Requests and interface request construction
Kotlin-Flow common encapsulation class: the use of StateFlow
1094 谷歌的招聘 (20 分)
MySql数据库
The problem that the rosbag tool plotjuggler cannot open rosbag