【web开发】5、Mysql及python代码执行数据库操作

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


一、MYSQL

数据库相当于我们常用的文件夹,数据表相当于我们常用说的文件,文件夹中存放文件,即数据库中存放数据表。当要创建一个新表时,需要选定某个数据库才能进行创建。

二、MySQL管理

查看已有数据库

show databases;  

在这里插入图片描述

创建数据库

create database 数据库名字 DEFAULT CHARSET utf8 COLLATE utf8_general_ci ;

create database demo2 DEFAULT CHARSET utf8 COLLATE utf8_general_ci ;

在这里插入图片描述

删除数据库

drop database 数据库名字;

 drop database demo2;

在这里插入图片描述

进入数据库

use 数据库名字;

 use demo1;

在这里插入图片描述
注意:查看数据表(show tables;);创建数据表(create table 数据表名),需要先进入文件夹再查看,即use 连接使用。

扫描二维码关注公众号,回复: 16706842 查看本文章

创建表

create table tb11(
-> id int primary key, //主键 不能为空,表示唯一标识
-> name varchar(16) not null, //不能为空,(16不能少)
-> age int null //可以为空 (最后一项不能有”,“)
-> )default charset=utf8;

create table tb11(
id int primary key, 
name varchar(16) not null,
age int null
)default charset=utf8;

注意: -> id int auto_increment primary key, //自增 1 2… √
在这里插入图片描述

删除表

drop table 表名称;

 drop table tb2;

在这里插入图片描述

展示表的行列

desc 表名称;

desc tb1;

在这里插入图片描述

插入数据

insert into 表名字(id,name,age) values(1,“aa”,20),(2,“bb”,21);

insert into tb1(id,name,age) values(1,"aa",20),(2,"bb",21);

在这里插入图片描述

查看表中的数据

select * from 表名字;

select * from tb1;

在这里插入图片描述

删除数据

delete from 表名字;
delete from 表名字 where 条件 ;
eg: delete from tb33 where id = 1;
delete from tb33 where id = 1 and name=”aa”;
delete from tb33 where id <=4;

delete from tb1 where id=1;

在这里插入图片描述

修改数据

update 表名字set 列=值;
update 表名字set 列=值,列=值;
update 表名字set age=age+10 where 条件;

update tb1 set name="cc";

在这里插入图片描述

三、python代码执行数据库操作

打开pycharm --创建新项目–终端写入pip(版本号) install pymysql

动态创建

(注意缩进)

import pymysql
while True:
    username=input("用户名:")
    if username.upper()=='Q':
        break
    password=input("密码:")
    mobile=input("手机号:")
# 1.连接MySQL
    conn=pymysql.connect(host="127.0.0.1",port=3306,user='root',passwd="12345",charset='utf8',db='unicom')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 2.发送指令  (不能用字符串格式化去做MySQL的拼接,有安全隐患)
    sql="insert into admin(username,password,mobile) values(%s,%s,%s)"
    cursor.execute(sql,[username,password,mobile])
    conn.commit()
# 3.关闭
    cursor.close()
    conn.close()

其中passwd="12345"表示进入数据库的密码,db='unicom’是新建的数据库名字,admin是新建表的名字,均可自行设置。

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

查询数据

全部数据: fetchall() 无数据为空列表
符合条件的第一个数据: fetchone() 无数据是none

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

# 2.执行查询的指令
cursor.execute("select * from  admin ",)
# %s是exceute的占位符,
rew=cursor.fetchone()
# print(data_list)
# 得出的结果是以字典形式展示列表中的数据
print(rew)
# 3.关闭
cursor.close()
conn.close()

在这里插入图片描述

删除数据

cursor.execute("delete from admin where id =%s",[8,])

8后面的逗号不能省略掉。

修改数据

cursor.execute("update admin set mobile=%s where id =%s",["49999999999",7,])

7后面的逗号不能省略掉。

猜你喜欢

转载自blog.csdn.net/qq_46644680/article/details/132766664