00下载pymysql
pip install pymysql
01查询操作
import pymysql
conn = pymysql.connect(host="localhost", port=3306, user="root", password="mysql", database="python_test_1", charset="utf8")
cs = conn.cursor()
sql = "select * from students;"
cs.execute(sql)
content = cs.fetchone()
print(content)
content = cs.fetchall()
print(content)
cs.close()
conn.close()
02增删改操作
import pymysql
conn = pymysql.connect(host="localhost", port=3306, user="root", password="mysql", database="python_test_1", charset="utf8")
cs = conn.cursor()
sql = "update students set name='老王' where id=1;"
cs.execute(sql)
sql = "select * from students;"
cs.execute(sql)
content = cs.fetchall()
for i in content:
print(i)
conn.commit()
cs.close()
conn.close()
03SQL注入
import pymysql
conn = pymysql.connect(host="localhost", port=3306, user="root", password="mysql", database="python_test_1", charset="utf8")
cs = conn.cursor()
find_name = input("请输入您要查询的学生姓名:")
sql = "select * from students where name=%s"
cs.execute(sql, [find_name])
content = cs.fetchall()
for i in content:
print(i)
cs.close()
conn.close()