import pymysql user = input('username: ') pwd = input('password: ') conn = pymysql.connect(host='127.0.0.1',user='root',password='123',database='db666') cursor = conn.cursor() sql = "select * from userinfo where username=%s and password=%s" # sql = "select * from userinfo where username=%(u)s and password=%(u)s" cursor.execute(sql,[user,pwd]) # cursor.execute(sql,{'u':user,'p':pwd}) result = cursor.fetchone() cursor.close() conn.close() print(result)
#增加
import pymysql
user = 'tim'
pwd = '123123'
conn = pymysql.connect(host='127.0.0.1',user='root',password='123',database='db666')
cursor = conn.cursor()
sql = "insert into userinfo(username,password) values(%s,%s)"
# cursor.execute(sql,(user,pwd))
cursor.executemany(sql,[('bim','ss'),('laoyao','ssb')])
conn.commit()
cursor.close()
conn.close()
#查 import pymysql conn = pymysql.connect(host='127.0.0.1',user='root',password='123',database='db666') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) #列表套字典 sql = "select * from userinfo" cursor.execute(sql) result = cursor.fetchone() print(result) result = cursor.fetchone() print(result) result = cursor.fetchall() print(result) cursor.close() conn.close()
import pymysql # user = input('username: ') # pwd = input('password: ') conn = pymysql.connect(host='127.0.0.1',user='root',password='123',database='db666') cursor = conn.cursor() sql = "insert into userinfo(username,password) values('ttt','123123')" cursor.execute(sql) conn.commit() print(cursor.lastrowid) #新插入数据的自增id cursor.close() conn.close()
python 实现用户登录
MySQL保存数据
-连接和关闭(游标)
- execute() 注意SQL注入问题
- 增删改: conn.commit()
- fetchone fetchall
- 获取插入数据的自增ID