python web连接mysql数据库
一定要commit,否则数据库不会发生改变!!!
1、使用python写入内容到数据库
import pymysql # 记得下载并引入pymysql
# 1、连接mysql,db:声明数据库
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注入
# sql = "insert into admin(id,username,password,mobile) values(111,'fxy','yyy','111')"
# 方式一
sql = "insert into admin(id,username,password,mobile) values(%s,%s,%s,%s)"
cursor.execute(sql,[1,"22","xxx","yyy"])
# 方式二
cursor.execute("insert into admin(id,username,password,mobile) values(%s,%s,%s,%s)")
conn.commit()
# 方式三
sql = "insert into admin(id,username,password,mobile) values(%(n1)s,%(n2)s,%(n3)s,%(n4)s)"
cursor.execute(sql,{"n1":2,"n2":"22","n3":"xxx","n4":"ssy"})
# 3、关闭连接
cursor.close()
conn.close()
#动态创建数据
import pymysql
while True:
id = input("id:")
if id == 0:
break
username = input("用户名:")
password = input("密码:")
mobile = input("手机号:")
# 1、连接mysql,db:声明数据库
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注入
# sql = "insert into admin(id,username,password,mobile) values(111,'fxy','yyy','111')"
# sql = "insert into admin(id,username,password,mobile) values(%s,%s,%s,%s)"
# cursor.execute(sql,[1,"22","xxx","yyy"])
sql = "insert into admin(id,username,password,mobile) values(%(n1)s,%(n2)s,%(n3)s,%(n4)s)"
cursor.execute(sql,{"n1":id,"n2":username,"n3":password,"n4":mobile})
conn.commit()
#3、关闭连接
cursor.close()
conn.close()
2、查询数据
import pymysql
# 连接数据库
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)
# 查询语句
# sql = "select * from admin"
cursor.execute("select * from admin")
# data_list = cursor.fetchall() # 获取数据返回的值,得到字典
data_list = cursor.one() # 获取一条数据
conn.commit()
#3、关闭连接
cursor.close()
conn.close()