使用MySQL内置工具(命令)
创建数据库:unicom
数据表:admin
表名:admin
列:
id 整型 自增 主键
username 字符串 不为空,
password 字符串 不为空,
mobile 字符串 不为空
Python代码实现
添加用户
删除用户
查看用户
更新用户信息
创建数据
1.创建表结构:
在数据库里先创建一个库名unicom,表名admin
create database unicom DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
use unicom;
create table admin(id int not null auto_increment primary key,
username varchar(16) not null,
password varchar(16) not null,
mobile char(11) not null
)default charset=utf8;
2.Python操作MySQL:
下载pymysql库:pip install pymysql
import pymysql
#1.连接MySQL
conn = pymysql.connect(host="127.0.0.1",port=3306,user="root",passwd="123456",charset="utf8",db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)#游标
#2.发送指令
cursor.execute("insert into admin(username,password,mobile) values('lsc','123456','12345678910')")
conn.commit()#提交指令
#3.关闭
cursor.close()
conn.close()
执行完上述代码后,admin表内已经写入数据
这两种方法也可以传值
sql="insert into admin(username,password,mobile) values(%s,%s,%s)"
cursor.execute(sql,["李明","234567","13992888888"])
sql="insert into admin(username,password,mobile) values(%(n1)s,%(n2)s,%(n3)s)"
cursor.execute(sql,{"n1":"丽丽","n2":"234567","n3":"13992888888"})
动态创建数据:
import pymysql
while True:
user = input("用户名")
if user.upper()=="X":
break
pwd = input("密码:")
mobile = input("手机号:")
#1.连接MySQL
conn = pymysql.connect(host="127.0.0.1",port=3306,user="root",passwd="123456",charset="utf8",db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)#游标
#2.发送指令
sql="insert into admin(username,password,mobile) values(%s,%s,%s)"
cursor.execute(sql,[user,pwd,mobile])
conn.commit()#提交指令
#3.关闭
cursor.close()
conn.close()
添加用户成功
查询数据
import pymysql
# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd="123456", charset="utf8", db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 游标
# 2.发送指令
cursor.execute("select * from admin")
data_list = cursor.fetchall()# :将返回所有结果,返回二维元组,如((‘id’,‘title’),(‘id’,‘title’)),
for row_dict in data_list:
print(row_dict)
# 3.关闭
cursor.close()
conn.close()
将数据库中数据返回列表内含字典的格式
data_list1 = cursor.fetchone()#筛选出来的第一条数据
data_list1 = cursor.fetchall()#获取筛选出来的所有数据
删除数据
import pymysql
# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd="123456", charset="utf8", db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 游标
# 2.发送指令
cursor.execute("delete from admin where id=%s",[2,])
conn.commit()
# 3.关闭
cursor.close()
conn.close()
id=2的数据被删除
修改数据
import pymysql
# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd="123456", charset="utf8", db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 游标
# 2.发送指令
cursor.execute("update admin set mobile=%s where id=%s",["17777777777",3,])
conn.commit()
# 3.关闭
cursor.close()
conn.close()
修改id=3的mobile
总结:
在进行新增,删除,修改时,要记得commit,不然数据库没有操作
在查询时,不需要commit,需要执行fetchall/fetchone