MySQL指令

MySQL指令

1.数据库管理

  • 查看已有的数据库(文件夹)

     show databases;
    
  • 创建数据库(文件夹)

    create database 数据库名字; #可能有汉字,编码方式可能不适用,产生乱码
    
    create database 数据库名字 DEFAULT CHARSET utf8 COLLATE utf8_general_ci ;
    #使用utf8编码,适用性较强
    
  • 删除数据库(文件夹),按上可以浏览以前的sql

    drop database 数据库名字;
    
  • 进入数据库(进入文件夹)

    use 数据库名字;
    
  • 查看数据库的表

    show tables;
    

2.数据表管理(文件)

  • 创建表

    create table 表名称(
    	列名称	类型,
      列名称	类型,
      列名称	类型
    )default charset=utf-8; #使用utf-8编码
    

    在这里插入图片描述

    例如:

    create table tb1(
    	id int not null auto_increment primary key, --内部维护,自增1,并声明为主键
      name varchar(16),
      age int
    ) default charset=utf8;
    
  • 删除表

    drop table 表名称;
    
  • 表的详细信息

    desc 表名;
    
    +---------------+---------------------+------+-----+---------+-------+
    | Field         | Type                | Null | Key | Default | Extra |
    +---------------+---------------------+------+-----+---------+-------+
    | events        | varchar(128)        | NO   |     | NULL    |       |
    | total         | bigint(20) unsigned | NO   |     | NULL    |       |
    | total_latency | bigint(20) unsigned | NO   |     | NULL    |       |
    | avg_latency   | bigint(20) unsigned | NO   |     | NULL    |       |
    | max_latency   | bigint(20) unsigned | NO   |     | NULL    |       |
    +---------------+---------------------+------+-----+---------+-------+
    

    数据类型见博主数据库专栏中的SQL简介。

  • 插入数据

    insert into 表名称(属性1,属性2,...) values (v11,v12,...),(v21,v22,...)... ;
    
  • 查看表中的数据:通过写query语句。

3.数据行操作

  • 新增数据

    insert into 表名(列名,...) values(,...),(,...);
    
    create table users(
    	id int not null primary key auto_increment,
      name varchar(64) not null,
      password varchar(64) not null,
      email varchar(64) not null,
      age tinyint,
      salary numeric(10,2),
      ctime datetime
    )default charset=utf8;
    
    #id是自增的,不用管,从1开始自动加1.
    insert into users(name,password,email,age,salary,ctime)
    values("两仪式","ryoushiki1980217","shiki@gmail.com",44,29402.50,"2024-3-31 10:50:25");
    
    insert into users(name,password,email,age,salary,ctime)
    values("黑桐干也","sjchDJ251c","GANYE@gmail.com",43,49402.50,"2024-3-31 10:50:25");
    
    insert into users(name,password,email,age,salary,ctime)
    values("浅织秋隆","automryoushiki","Qiu@gmail.com",74,5042.50,"2024-3-31 10:50:25");
    insert into users(name,password,email,age,salary,ctime)
    values("苍崎橙子","cccccORANGE","orange@gmail.com",54,39402.50,"2024-3-31 10:50:25");
    
    insert into users(name,password,email,age,salary,ctime)
    values("荒耶宗莲","123456789","HuangYe@gmail.com",65,1.50,"2024-3-31 10:50:25");
    
  • 删除数据

    delete from 表名;
    delete from 表明 where 条件;
    
  • 修改数据

    update 表名	set 列名=where 条件;
    
    update users set salary=0.5*salary where id=5;
    
  • 查询数据,query语句

案例:员工管理

  • 使用MySQL内置工具(命令)

    • 创建数据库:unicom

    • 数据表:admin

      表名:admin
      列:
      	id,整型,自增,主键
      	username 字符串 不为空
      	password 字符串 不为空
      	mobile   字符串 不为空
      	
      
      
  • Python代码实现

    • 添加用户
    • 删除用户
    • 查看用户
    • 更新用户信息

1.创建表结构

create database unicom DEFAULT CHARSET utf8 COLLATE utf8_general_ci ;
create table users(
	id int not null primary key auto_increment,
  username varchar(30) not null,
  password varchar(64) not null,
  mobile varchar(13) not null
)default charset=utf8;

2.Python 操作MySQL

用Python 代码连接MySQL并发送指令

pip install pymysql
2.1 创建数据库
import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="localhost", port=3306, user="root", passwd="horse030811", charset="utf8", db="unicom")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令(千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入)
# sql="insert into users(username,password,mobile) values({},{},{})".format("bill","12312","12412")
cursor.execute("insert into users(username,password,mobile) values('asmsxw','qwe123','1245251232')")
# 使用pymysql内部的占位语句
sql = "insert into users(username,password,mobile) values(%s,%s,%s"
cursor.execute(sql, ["shiki", "qwer123", "124512346"])

# 也可以给占位符起名,使用字典。
sql = "insert into users(username,password,mobile) values(%(n1)s,%(n2)s,%(n3)s"
cursor.execute(sql, {"n1": "alice", "n2": "gasdlk1245", "n3": "6134132"})

conn.commit()

# 3.关闭
cursor.close()
conn.close()
#动态的用户输入
import pymysql

while True:
    user = input("用户名:")
    if user.upper() == 'Q':
        break
    pwd=input("密码:")
    mobile = input("手机号:")

    # 1.连接MySQL
    conn = pymysql.connect(host="localhost", port=3306, user="root",   passwd="horse030811", charset="utf8", db="unicom")
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

    # 2.发送指令(千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入)
    # 使用pymysql内部的占位语句
    sql = "insert into users(username,password,mobile) values(%s,%s,%s)"
    cursor.execute(sql, [user, pwd , mobile])

    conn.commit()

    # 3.关闭
    cursor.close()
    conn.close()
2.2 查询数据
import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="localhost", port=3306, user="root", passwd="horse030811", charset="utf8", db="unicom")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令(千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入)
# 使用pymysql内部的占位语句
sql = "select * from users "
cursor.execute(sql)
datalist = cursor.fetchall()  # 发送指令后,数据库会输出相应值,使用fetchall获取值
sql = "select * from users where id>2 "
cursor.execute(sql)
dataone = cursor.fetchone()  # 取出符合query的第一条数据
print(datalist)  # 以字典键值对的形式返回
print("fetchall:")
for row_dict in datalist:
    print(row_dict)

print("fetchone:", dataone)  #{'id': 3, 'username': 'shiki', 'password': 'qwer123', 'mobile': '124512346'}


# 3.关闭
cursor.close()
conn.close()
2.3 删除数据
import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="localhost", port=3306, user="root", passwd="horse030811", charset="utf8", db="unicom")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令(千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入)
# 使用pymysql内部的占位语句
sql = "delete from users where id =%s"
cursor.execute(sql, [1, ])

conn.commit()

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

2.4 修改数据
import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="localhost", port=3306, user="root", passwd="horse030811", charset="utf8", db="unicom")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令(千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入)
# 使用pymysql内部的占位语句
sql = "update users set mobile=%s where id=%s"
cursor.execute(sql, [18619802174, 3])

conn.commit()

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

注意

  • 在执行完query后,一定要commit,数据库才会更新,否则会回滚。

  • 查询不用commit,因为没有更新数据库,需要执行fetchall/fetchone

  • SQL语句不要用Python的字符串格式化进行拼接,用execute+参数

    	cursor.execute(sql,[x,y,..])
    

案例:Flask+MySQL

1.新增用户

from flask import Flask, render_template, request
import pymysql

app = Flask(__name__)


@app.route('/add/user', methods=["GET", "POST"]) 
	#前面是网址路径methods表明支持两种提交方式
def add_user():
    if request.method == "GET":
        return render_template("add_user.html")

    print(request.form)  # 可得到字典形式的表单数据:ImmutableMultiDict([('user', '阿斯顿金克拉'), ('pwd', 'zxlcas'), ('mobile', '1258912557')])

    username = request.form.get("user")  # 得到单个键的值
    password = request.form.get("pwd")
    mobile = request.form.get("mobile")

    # 1.连接MySQL
    conn = pymysql.connect(host="localhost", user="root", passwd="horse030811", charset="utf8", db="unicom")
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 指定了使用字典类型的游标(cursor),这通常用于 MySQL 查询结果的返回。
    # 2.执行SQL
    sql = "insert into users(username,password,mobile) values(%s,%s,%s)"
    cursor.execute(sql, [username, password, mobile])

    conn.commit()
    # 3。关闭连接
    cursor.close()
    conn.close()

    return "asasdasd"


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

HTML部分
#一个简单的表单,注意name对应的是键名
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>添加用户</h1>
<form method="post" action="/add/user">
    <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>

2.查询用户

@app.route('/show/user', methods=["GET", "POST"])
def show_user():
    # 1.连接MySQL
    conn = pymysql.connect(host="localhost", user="root", passwd="horse030811", charset="utf8", db="unicom")
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 指定了使用字典类型的游标(cursor),这通常用于 MySQL 查询结果的返回。
    # 2.执行SQL
    sql = "select * from users"
    cursor.execute(sql)
    data_list = cursor.fetchall()

    conn.commit()
    # 3。关闭连接
    cursor.close()
    conn.close()

    print(data_list)

    return render_template('show_user.html',data=data_list)#传入data_list为data

HTML部分
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<table border="1">
    <thead>
        <th>ID</th>
        <th>姓名</th>
        <th>密码</th>
        <th>手机号</th>
    </thead>
    <tbody>

    {% for item in data %}
        <tr>
            <td>{{ item.id}}</td>
            <td>{{item.username}}</td>
            <td>{{item.password}}</td>
            <td>{{item.mobile}}</td>
        </tr>
    {% endfor %}

    </tbody>
</table>
</body>
</html>
  • 27
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值