django web开发(二)Mysql基础

mysql

官网:https://www.mysql.com/

1 mysql使用

C:\Windows\System32> mysql -u root -p

输入密码

mysql> show databases;

展示数据库

在这里插入图片描述退出

mysql> exit;

2 mysql重新设置密码

  • 停用MySQL服务

在这里插入图片描述

  • 修改mysql文件

添加 skip-grant-tables=1

在这里插入图片描述
无需密码即可进入
在这里插入图片描述输入命令mysql -u root -p指定 root 用户登录 MySQL,输入后按回车键输入密码。如果没有配置环境变量,请在 MySQL 的 bin 目录下登录操作。

输入use mysql;命令连接权限数据库。

输入命令update mysql.user set authentication_string=password(‘新密码’) where user=‘用户名’ and Host =‘localhost’;设置新密码。

输入 flush privileges; 命令刷新权限。

输入quit;命令退出 MySQL 重新登录,此时密码已经修改为刚才输入的新密码了。
在这里插入图片描述修改回配置文件
在这里插入图片描述

3 数据库管理

--创建数据库
create database dbname DEFAULT CHARSET  utf8 COLLATE utf8_general_ci;
							
--删除数据库
drop database dbname;

--进入数据库
use dbname;

--查看数据表
show tables;

4 数据表管理

创建表

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

create table tb1(
		id int,
		name varchar(16) not null, --不允许为空
		age int	
)default charset=utf8;
create table tb1(
		id int,
		name varchar(16),
		age int	default 3    --默认值为3
)default charset=utf8;
create table tb1(
		id int primary key,   --主键(不空不重)
		name varchar(16),
		age int	
)default charset=utf8;

一般:

create table tb1(
		id int not null auto_increment primary key, --id自增非空
		name varchar(16),
		age int	
)default charset=utf8;

查看表

desc 表名称;

在这里插入图片描述

删除表

drop table 表名称;

5 常用数据类型

整数

  • tinyint

有符号, 取值范围: -128 ~ 127(有正有负)
无符号, 取值范围: 0 ~ 255(只有正)

create table tb1(
	id int not null auto_increment primary key,
	age tinyint				--有符号, 取值范围: -128 ~ 127
) default charset=utf8;

create table tb1(
	id int not null auto_increment primary key,
	age tinyint unsigned	--无符号, 取值范围: 0 ~ 255
) default charset=utf8;
  • int

有符号, 取值范围: -2147483648 ~ 2147483647(有正有负)
无符号, 取值范围: 0 ~ 4294967295(只有正)

  • bigint

有符号, 取值范围: -9223372036854775808 ~ 9223372036854775807(有正有负)
无符号, 取值范围: 0 ~ 18446744073709551615(只有正)

小数

  • float

  • double

  • decimal(精准小数值,m最大65,小数位数最大30)

create table tb1(
	id int auto_increment primary key,		--内部维护,自增
	name varchar(16),
	salary decimal(8,2)						--一共8位(整数位数+小数点位数), 保留小数点后2位
) default charset=utf8;

字符串

  • char

定长字符串
默认固定用 11 个字符串进行存储,哪怕字符串个数不足,也按照11个字符存储
最多能存储255个字节的数据
查询效率高

  • varchar

变长字符串
默认最长 11 个字符,真实数据多长就按多长存储
最多能存储 65535 个字节的数据,中文可存储 65535/3 个汉字
相对 char 类型, 查询效率低

  • text

变长字符串
默认最长 11 个字符,真实数据多长就按多长存储
最多能存储 65535 个字节的数据,中文可存储 65535/3 个汉字
相对 char 类型,查询效率低

  • mediumtext

  • longtext

大字符串

时间

  • datetime

YYYY-MM-DD HH:MM:SS (1000-01-01 00:00:00/9999-12-31 23:59:59)

  • date

YYYY-MM-DD (1000-01-01/9999-12-31)

案例:用户表

create table user(
	id int not null primary key auto_increment,
	name varchar(64),
	password varchar(64),
	age tinyint,
	salary decimal(10,2),
	ctime datetime
)default charset=utf8;

6 数据管理

插入表行数据

insert into tb2(salary,age) values(5024,(100,30);

查看表数据

select 列名,列名 from 表名称 where 条件;
--ed
select *from tb2;
select id,name from where name="sxk" and password ="123";

删除数据

delete from 表名;--删除整个表
delete from 表名 where 条件;
--ed
delete from tb where id = 3 and name="sxk";
id >2;
id in (1,5);

修改数据

updata 表名 set=“值” where id <3;
--ed
updata tb set age=age+10 where age <3;

案例:员工管理

创建表

使用Mysql内置工具(命令)
创建数据库: uu
创建数据表: aa
列:
id 整型 自增 主键
username: 字符串 不为空
password: 字符串 不为空
mobile: 字符串 不为空

mysql> create table aa(
    -> id int primary key auto_increment,
    -> username char(30) not null,
    -> password char(30) not null,
    -> mobile char(30) not null)default charset=utf8
    -> ;

在这里插入图片描述

python创建数据

创建数据

import pymysql

# 链接mysql
conn =  pymysql.connect(host='127.0.0.1', port=3306,user='root' , password='root',charset='utf8',db="uu")
cursor =conn.cursor()

# 发送指令
cursor.execute("insert into aa(username,password,mobile) values ('sxk','123','123456')")
conn.commit()

# 关闭
cursor.close()
conn.close()

在这里插入图片描述
优化:手动输入



import pymysql

while True:
    u = input("用户名")
    if u.upper() == 'Q':
        break


    p = input("密码:")
    m = input("手机")
    # 链接mysql
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root', charset='utf8', db="uu")
    cursor = conn.cursor()

    # 发送指令
    sql = "insert into aa(username,password,mobile) values (%s, %s, %s);"
    cursor.execute(sql, [u, p, m])
    conn.commit()

    # 关闭
    cursor.close()
    conn.close()

在这里插入图片描述

python查询数据

# author : Sun;  time : 2023/2/3 17:02;
import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root', charset='utf8', db="uu")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

sql = "select * from aa where id>=3"
cursor.execute(sql)
# data_list = cursor.fetchall()		查询一条数据,为字典
data_list = cursor.fetchall()	 #查询所有符合条件的数据,为列表套多个
print(data_list )

# 关闭
cursor.close()
conn.close()

输出一个列表套字典:[{字典} ,{字典} …]

[{'id': 3, 'username': 'kk', 'password': '321', 'mobile': '1232121'}, 
{'id': 4, 'username': 'uu', 'password': '135', 'mobile': '12513535'}]

python删除数据

# author : Sun;  time : 2023/2/3 17:02;
import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root', charset='utf8', db="uu")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

sql = "delete from aa where id =%s"
cursor.execute(sql, [2])
conn.commit()

sql = "select * from aa"
cursor.execute(sql)

data_list = cursor.fetchall()

for i in data_list:
    print(i)

# 关闭
cursor.close()
conn.close()

在这里插入图片描述

python修改数据

# author : Sun;  time : 2023/2/3 17:02;
import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root', charset='utf8', db="uu")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

sql = "update aa set mobile=%s where id =%s"
cursor.execute(sql, [88888888,1,])
conn.commit()

sql = "select * from aa"
cursor.execute(sql)

data_list = cursor.fetchall()

for i in data_list:
    print(i)

# 关闭
cursor.close()
conn.close()

在这里插入图片描述

总结

在进行新增、删除、修改时进行,,,不然没有数据
cursor.execute(sql)
conn.commit()

import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root', charset='utf8', db="uu")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

sql = "sql语句"
cursor.execute(sql)
conn.commit()

# 关闭
cursor.close()
conn.close()

查询时不需要commit
执行fetchall/fachone

import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root', charset='utf8', db="uu")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)


sql = "select * from aa"
cursor.execute(sql)
#所有数据,列表套字典,无数据为None
data_list = cursor.fetchall()
#第一条数据,字典,无数据为空列表 
data_list = cursor.fetchone() 


# 关闭
cursor.close()
conn.close()

案例:flask + mysql

main.py

from flask import Flask, render_template, request
import pymysql

app = Flask(__name__)


@app.route("/aduser", methods=["POST", "GET"])
def aduser():
    if request.method == "GET":
        return render_template("xaduser.html")
    else:
        un = request.form.get("user")
        pwd = request.form.get("pwd")
        mb = request.form.get("mobile")

        conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root', charset='utf8', db="uu")
        cursor = conn.cursor()

        sql = "insert into aa(username,password,mobile) values (%s,%s,%s);"
        cursor.execute(sql, [un, pwd, mb])
        conn.commit()

        cursor.close()
        conn.close()

        print(un, pwd, mb)
        return "添加成功"


@app.route("/shuser", methods=["POST", "GET"])
def shuer():
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root', charset='utf8', db="uu")
    # 返回类型为元组类型
    cursor = conn.cursor()

    sql = "select * from aa"
    cursor.execute(sql)
    data = cursor.fetchall()

    cursor.close()
    conn.close()

    return render_template("xshuser.html", data = data)


if __name__ == '__main__':
    app.run()

xaduser.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1> 添加用户</h1>
<form method="post" action="/aduser">

<input type="text" name="user" placeholder="用户名">
<input type="text" name="pwd" placeholder="密码">
<input type="text" name="mobile" placeholder="手机号">
<input type="submit" value="提交">

</form>
</body>
</html>

在这里插入图片描述在这里插入图片描述

xshuser.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>展示列表</h2>


<div id="app">
    <table>
        <thead>
        <tr>
            <th>id</th>
            <th>username</th>
            <th>pwd</th>
            <th>moobile</th>
        </tr>
        </thead>
        <tbody>
                {% for d in data %}
                <tr>
                    <th>{{ d[0] }}</th>
                    <th>{{d[1]}}</th>
                    <th>{{d[2]}}</th>
                    <th>{{d[3]}}</th>
                </tr>
                {% endfor %}
    </table>
</div>
</body>
</html>

在这里插入图片描述

占位符

  1. 找到xshuser.html的文件,读取所有内容
  2. 找到特殊占位符,将数据替换
  3. 将替换完成的字符串返回给用户
	...
    sql = "select * from aa"
    cursor.execute(sql)
    data = cursor.fetchall()
    ...
    return render_template("xshuser.html", data = data)

data为元组类型.

                {% for d in data %}
                <tr>
                    <th>{{ d[0] }}</th>
                    <th>{{d[1]}}</th>
                    <th>{{d[2]}}</th>
                    <th>{{d[3]}}</th>
                </tr>
                {% endfor %}

加入bootstrap

 <link rel="stylesheet" href="../static/plugins/bootstrap-3.4.1/css/bootstrap.css"
....
 <table class="table table-bordered">

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python是一种面向对象且高级的编程语言,已经成为Web开发,数据科学和机器学习等领域的首选。Django是基于Python的开源Web框架,使Web开发更加容易、快速和可扩展。属于MVT(Model-View-Template)架构,通过它可以快速地开发出一个大型的Web应用程序。MySQL是一种功能强大和广泛应用的关系型数据库管理系统,适用于广泛范围的Web应用程序开发。最近几年, MySQL在极高的性能、与其他应用程序的无缝集成、易于维护等方面成为了Web开发的首选数据库。 结合这些技术,我们可以完成各种Web应用程序的开发,例如电子书。电子书是指以电子文档的形式发行的图书或书籍,具有较高的便携性和使用方式,不需要纸质印刷。以Python为基础,并使用Django框架和MySQL作为后端数据库管理系统,能够实现电子书的在线阅读、购买和下载等。利用Django模板和静态文件,我们可以构建电子书的外观和用户界面。还能够使用Django的内置功能,例如用户身份验证和身份管理,来确保用户安全访问电子书。同时,使用MySQL数据库,可以存储电子书的元数据和用户购买记录,并使用ORM(对象关系映射)模式轻松访问和管理这些数据。 总的来说,使用Python,DjangoMySQL可以简化Web应用程序的开发,特别是在开发诸如电子书等复杂应用程序时,这三种技术可以相互促进,提高开发效率和软件质量。 ### 回答2: 电子书Python Django MySQL开发Web指的是使用Python语言编写的Django框架,通过MySQL数据库实现Web开发的过程。这种开发方式具有高效且易于维护的特点,并且具有强大的扩展性和灵活性。 Python是一种高级编程语言,具有语法简单、易于学习及强大的编程能力等多方面的优势,在Web开发领域具有广泛应用。而Django是一个基于Python的Web框架,它的开发目的是为了简化Web应用程序的创建过程,提供高效一致的解决方案。 MySQL是一种开源的关系型数据库管理系统,它具有高效性、稳定性、可扩展性等多种优点,适合大型Web开发项目的数据库管理。 在实际的开发中,在Python语言中使用Django框架连同MySQL数据库可以轻松地实现Web应用的创建和管理。由于Django提供的高级开发工具和自动化管理机制,开发人员可以轻松地处理常见的Web开发任务,节省工作时间。 总而言之,电子书Python Django MySQL开发Web是一种高效、灵活、易于维护的Web开发方式。它可以帮助开发人员快速创建高品质的Web应用,同时更好地满足项目需求,进而为用户带来更出色的使用体验。 ### 回答3: 电子书是目前最受欢迎的阅读方式之一,Python是一种广泛使用的编程语言,Django是一个流行的Web框架,MySQL是一种常见的关系型数据库。这些工具的结合可以帮助开发人员快速构建高效的Web应用程序。 使用Python和Django可以快速搭建一个Web应用程序的框架,然后可以使用MySQL来存储和管理数据。在这个过程中,可以使用Python的各种库和模块来扩展应用程序的功能,包括更高级的图形用户界面、数据可视化和其他功能。 与传统的书籍不同,电子书可以提供更丰富的媒体和互动体验,比如可以包含多媒体内容、链接和动画。Python和Django可以帮助开发人员构建更具交互性和视觉吸引力的Web应用程序,并且还可以使用MySQL来存储和检索更复杂的数据。 总之,电子书python django mysql开发web是一种非常强大的工具组合,可以帮助开发人员快速构建高效、易于使用和易于管理的Web应用程序。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值