zoukankan      html  css  js  c++  java
  • 数据库进行参数化,查询一行或多行语句

    参数化
    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

  • 相关阅读:
    runtest.sh
    写代码:简单的三元运算
    写代码:用户交互显示类似省市县三级联动的选择
    写代码:列举布尔值是False的所有值
    写代码:求集合
    写代码:利用For循环和while输出1-100
    写代码:利用for循环和range输出9*9乘法表
    写代码:查找列表中元素,移除每个元素的空格,并查找以a或A开头并且以c结尾的元素。
    写代码:利用下划线将列表的每个元素拼接成字符串,li=["alex","eric","rain"]
    写代码:购物车程序
  • 原文地址:https://www.cnblogs.com/hany-postq473111315/p/12845325.html
Copyright © 2011-2022 走看看