2023.10.22使用python进行sql查询

2023.10.22使用python进行sql查询

在mysql中创建数据库
在这里插入图片描述

'''
测试用例
'''
import  pymysql

# 远程连接宝塔面板上的数据库
conn = pymysql.Connect(
        host="服务器IP地址",
        user="数据库用户名",
        password="数据库密码",
        database="数据库名",
        port = 3306,  # 端口号,默认即3306
        charset = "utf8"    # 需要设置utf-8,否则取不到中文
)

# cursor = conn.cursor()    # 一般取数据的方法,以列表的形式取数据
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)     # 以字典的形式取数据

# cursor.execute('select * from user_info')     # 选择所有数据表中的数据

# 防止sql语句注入,不能直接用字符串格式拼接sql语句,否则可以通过模糊查询方式进行注入攻击,如下为错误写法
# sql = "select * from user_info where name='%s' and password = '%s'"%('lisi','567')

# 注意参数名称和数据库的字段名称需一致,正确的防止sql注入写法如下:
cursor.execute('select * from user_info where name=%s and password = %s',('lisi','567'))

# 可以传字典
# cursor.execute('select * from user_info where name=%(na)s and password = %(pa)s',{'na':'zhangshan','pa':'666'})
# cursor.execute('select * from user_info where name=%(name)s and password = %(password)s',{'name':'zhangshan','password':'666'})
# data = cursor.fetchall()    # 取出全部数据
data = cursor.fetchone()    # 取出匹配成功的第一条数据

cursor.close()
conn.close()
print(data)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

leigh_chen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值