数据库进行参数化,查询一行或多行语句

参数化
from pymysql import *

def main():
    find_name = input("请输入物品名称")
    conn = connect(host='localhost',port=3306,user='root',password='root',database='jing_dong',charset='utf8')
    # 主机名、端口号、用户名、密码、数据库名、字符格式
    cs1 = conn.cursor()#获取游标
    # 构成参数列表
    params = [find_name]
    # 对查询的数据,使用变量进行赋值
    count = cs1.execute('select * from goods where name=%s'%(params))

    print(count)

    result = cs1.fetchall()
    # 输出所有数据
    print(result)
    # 先关闭游标、后关闭连接
    cs1.close()
    conn.close()

if __name__ == '__main__':
    main()

查询一行语句
from pymysql import *
import time

def main():
    # 创建Connection连接
    conn = connect(host='localhost',port=3306,user='root',password='root',database='jing_dong',charset='utf8')
    # 获得Cursor对象
    cs1 = conn.cursor()
    # 执行select语句,并返回受影响的行数:查询一条数据
    count = cs1.execute('select id,name from goods where id>=4')
    # count = cs1.execute('select id,name from goods where id between 4 and 15')
    # 打印受影响的行数
    print("查询到%d条数据:" % count)

    for i in range(count):
        # 获取查询的结果
        result = cs1.fetchone() #每次只输出一条数据 fetchall全部输出
        # 打印查询的结果
        time.sleep(0.5)
        print(result)
        # 获取查询的结果


    # 关闭Cursor对象
    cs1.close()
    conn.close()

if __name__ == '__main__':
    main()

from pymysql import *

def main():
    # 创建Connection连接
    conn = connect(host='localhost',port=3306,user='root',password='root',database='jing_dong',charset='utf8')
    # 获得Cursor对象
    cs1 = conn.cursor()
    # 执行select语句,并返回受影响的行数:查询一条数据
    count = cs1.execute('select id,name from goods where id>=4')
    # 打印受影响的行数
    print("查询到%d条数据:" % count)

    # for i in range(count):
    #     # 获取查询的结果
    #     result = cs1.fetchone()
    #     # 打印查询的结果
    #     print(result)
    #     # 获取查询的结果

    result = cs1.fetchall()#直接一行输出
    print(result)

    # 关闭Cursor对象
    cs1.close()
    conn.close()

if __name__ == '__main__':
    main()

2020-05-07

原文地址:https://www.cnblogs.com/hany-postq473111315/p/12845325.html