python 操作 mysql
#######select
import pymysql
# 获取数据
conn = pymysql.Connect(host='192.168.12.89',port=3306,user='root',password="123",database="s17day11db",charset='utf8')
cursor = conn.cursor()
# 受影响的行数
v = cursor.execute('select * from student')
result = cursor.fetchall()
# result = cursor.fetchone()
# result = cursor.fetchmany(2)
print(result)
cursor.close()
conn.close()
###########other
# 获取数据
conn = pymysql.Connect(host='192.168.12.89',port=3306,user='root',password="123",database="s17day11db",charset='utf8')
cursor = conn.cursor()
# 受影响的行数
v = cursor.execute('insert into userinfo(username,password) values(%s,%s)',['eric','99999'])
conn.commit()
v = cursor.execute('delete from userinfo where username=%s',['eric'])
conn.commit()
v = cursor.execute('update userinfo set password=%s where username=%s',['999999','alex'])
conn.commit()
cursor.close()
conn.close()
#################需求
新创建一个班级,并且 创建一个学生 加入这个班级
import pymysql
# 获取数据
conn = pymysql.Connect(host='192.168.12.89',port=3306,user='root',password="123",database="s17day11db",charset='utf8')
cursor = conn.cursor()
cursor.execute('insert into class(caption) values(%s)',['新班级'])
conn.commit()
new_class_id = cursor.lastrowid # 获取新增数据自增ID
cursor.execute('insert into student(sname,gender,class_id) values(%s,%s,%s)',['李杰','男',new_class_id])
conn.commit()
cursor.close()
conn.close()
解释:可以通过cursor.lastrowid 获取到 本脚本中执行的 自增ID
然后放入吓一条sql中
#####################################被sql注入的写法, 以及 sql注入
import pymysql
user = input('请输入用户名:')
pwd = input('请输入密码:')
# 获取数据
conn = pymysql.Connect(host='192.168.12.89',port=3306,user='root',password="123",database="s17day11db",charset='utf8')
cursor = conn.cursor()
sql = 'select * from userinfo where username="%s" and password="%s" ' %(user,pwd,)
# user = alex" --
# pwd= asdf
'select * from userinfo where username="alex" -- " and password="sdfsdf"'
# user = asdfasdf" or 1=1 --
# pwd= asdf
'select * from userinfo where username="asdfasdf" or 1=1 -- " and password="asdfasdf"'
v = cursor.execute(sql)
result = cursor.fetchone()
cursor.close()
conn.close()
print(result)
###################防止sql注入
import pymysql
user = input('请输入用户名:')
pwd = input('请输入密码:')
# 获取数据
conn = pymysql.Connect(host='192.168.12.89',port=3306,user='root',password="123",database="s17day11db",charset='utf8')
cursor = conn.cursor()
sql = 'select * from userinfo where username="%s" and password="%s" ' %(user,pwd,)
# user = alex" --
# pwd= asdf
'select * from userinfo where username="alex" -- " and password="sdfsdf"'
# user = asdfasdf" or 1=1 --
# pwd= asdf
'select * from userinfo where username="asdfasdf" or 1=1 -- " and password="asdfasdf"'
v = cursor.execute(sql)
result = cursor.fetchone()
cursor.close()
conn.close()
print(result)