pymysql模块

#pip3 install pymysql
import pymysql

user=input('user>>: ').strip()
pwd=input('password>>: ').strip()

# 创建连接
conn=pymysql.connect(
    host='192.168.1.16',
    port=3306,
    user='root',
    password='123',
    db='db1',
    charset='utf8'
)

# 拿到游标
cursor=conn.cursor() #执行完毕返回的结果集默认以元组显示
#cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)  #

# sql注入之:用户不存在,绕过用户与密码 aaa' or 1=1 -- 任意字符
# sql='select * from userinfo where user = "%s" and pwd="%s"' %(user,pwd)
# print(sql)

#改写为(execute帮咱们作字符串拼接,咱们无需且必定不能再为%s加引号了)由于pymysql会自动为咱们加上,pymysql模块自动帮咱们解决sql注入的问题
sql='select * from userinfo where user = %s and pwd=%s'
rows=cursor.execute(sql,(user,pwd)) #执行sql语句,返回sql查询成功的记录数目

# print(cursor.fetchone())
# print(cursor.fetchall())
# print(cursor.fetchmany(2))   #通常不用直接用limit控制数量

# cursor.scroll(3,mode='absolute') # 相对绝对位置移动
# print(cursor.fetchone())
# cursor.scroll(2,mode='relative') # 相对当前位置移动
# print(cursor.fetchone())

# 增、删、改 须要提交:conn.commit()  #提交后表中记录才会变更
sql99='insert into userinfo(user,pwd) values(%s,%s)'

rows99=cursor.execute(sql99,('tom','123'))#单条
print(rows99)

rows99=cursor.executemany(sql99,[('jack','123'),('rose','111'),('tony','2222')])#多条
print(rows99)

print(cursor.lastrowid)# 获取插入的最后一条数据的自增ID

conn.commit()# 增、删、改 须要提交:conn.commit()  #提交后表中记录才会变更

cursor.close()
conn.close()

# 进行判断
if rows:
    print('登陆成功')
else:
    print('登陆失败')

"""
按年月分组查询
select  date_format(sub_time,'%Y-%m'),count(id) from blog group by date_format(sub_time,'%Y-%m')
"""
相关文章
相关标签/搜索