insert into 表名(列名,列名) values(值,值)
insert into 表名(列名,列名) values(值,值),(值,值),(值,值),(值,值);
delete from表名
delete from 表名 where 条件
update 表名 set 列 = 值
update 表名 set 列 = 值,列 = 值
update 表名 set 列 = 值 where 条件
select * from 表名称
select 列名称,列名称 from 表名称
select 列名称,列名称 from 表名称 where 条件
创建数据库unicom
create database unicom DEFAULT CHARSEF utf8 COLLATE utf8_general_ci;
进入数据库
use unicom
创建数据表admin
create table admin(
id int not null auto_increment primary key,
username varchar(16) not null,
password varchar(64) not null,
mobile char(11) not null
) default charset=utf8;
用python代码连接MySQL并发送指令
pip install pymysql
import pymysql
# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1",port=3306,user='root',passwd="root123",charset='utf8',db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 2.发送指令(千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入,可以用pymysql中的%s占位符)
# sql = "insert into admin(username,password,mobile) values('zhangsan','123','15120123246')"
# cursor.execute(sql)
# sql = "insert into admin(username,password,mobile) values(%s,%s,%s)"
# cursor.execute(sql,['张三','1123','15120432232'])
sql = "insert into admin(username,password,mobile) values(%(n1)s,%(n2)s,%(n3)s)"
cursor.execute(sql,{"n1":"张三","n2":"123","n3":"15120432312"})
conn.commit()
# 3.关闭连接
cursor.close()
conn.close()
import pymysql
# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1",port=3306,user='root',passwd="root123",charset='utf8',db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 2.发送指令(千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入,可以用pymysql中的%s占位符)
sql = "select * from admin"
cursor.execute(sql)
data_list = cursor.fetchall() # fetchall获取数据库返回的所有值,fetchone获取符合条件的第一条数据
conn.commit()
# 3.关闭连接
cursor.close()
conn.close()
import pymysql
# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1",port=3306,user='root',passwd="root123",charset='utf8',db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 2.发送指令(千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入,可以用pymysql中的%s占位符)
sql = "delete from admin where id = %s"
cursor.execute(sql,[3,])
conn.commit()
# 3.关闭连接
cursor.close()
conn.close()
import pymysql
# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1",port=3306,user='root',passwd="root123",charset='utf8',db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 2.发送指令(千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入,可以用pymysql中的%s占位符)
sql = "update admin set mobile=%s where id = %s"
cursor.execute(sql,["15120432654",4, ])
conn.commit()
# 3.关闭连接
cursor.close()
conn.close()
cursor.execute("...")
conn.commit()
cursor.execute("...")
# 所有数据,列表套字典,无数据时是none
data_list = cursor.fetchall() # fetchall获取数据库返回的所有值,fetchone获取符合条件的第一条数据
# 第一条数据,字典,无数据时是空列表
data_list = cursor.fetchone()
conn.commit()
cursor.execute(".%s....%s",["xx","xx"])