MySQL【五】与python交互

1.安装pymysql

 安装pymysql

pip install pymysql

2.游标(cursor)的使用

cursor,就是一个标识,用来标识数据可以理解成数组中的下标  。

一、声明一个游标: declare 游标名称 CURSOR for table;(这里的table可以是你查询出来的任意集合)
    二、打开定义的游标:open 游标名称;
    三、获得下一行数据:FETCH  游标名称 into testrangeid,versionid;
    四、需要执行的语句(增删改查):这里视具体情况而定
    五、释放游标:CLOSE 游标名称;

  • 首先fetchone()函数它的返回值是单个的元组,也就是一行记录,如果没有结果,那就会返回null
  • 其次是fetchall()函数,它的返回值是多个元组,即返回多个行记录,如果没有结果,返回的是()
  • fetchall(参数),写几条返回几条
#举个例子:cursor是我们连接数据库的实例

fetchone()的使用:

cursor.execute(select username,password,nickname from user where id='%s'  %(input)

result=cursor.fetchone();  此时我们可以通过result[0],result[1],result[2]得到username,password,nickname

fetchall()的使用:

cursor.execute(select * from user)

result=cursor.fetchall();此时select得到的可能是多行记录,那么我们通过fetchall得到的就是多行记录,是一个二维元组

((username1,password1,nickname1),(username2,password2,nickname2),(username3,password3,nickname))

简单demo:

from pymysql import *


# pymysql操作数据库流程:开始-创建connection-获取cursor-mysql语句-关闭cursor-关闭connection-结束

def main():
    #创建connection连接  连接对象
    conn = connect(host = "localhost", port = 3306, user = 'root', password = '123456', database = 'jing_dong', charset = 'utf8')

    #获取Cursor对象  游标对象
    cs1 = conn.cursor()
    count = cs1.execute('select id, name from goods where id > 4')  #execute写sql语句
    print("打印受影响的行数:", count)

    # print(cs1.fetchall())
    # print(cs1.fetchmany(2))
    for i in range(count):
        #获取查询的结果
        result = cs1.fetchone() #返回一个元组一条一条取  fetchmany()和fetchall()返回的结果是元组套元组
        print(result)
        
    #关闭cursor,关闭连接
    cs1.close()
    conn.close()

if __name__ == '__main__':
    main()

根据实际需求选择对应fetch函数

line=cursor.fetchone()

line[0]
line[1]
#一列一列取出

lines=cursor.fetchmany(5)
for temp in lines:
    print(temp)
#一个元组一个元组取出

3.京东商城查询

python staticmethod 返回函数的静态方法。

该方法不强制要求传递参数,如下声明一个静态方法:

class C(object):
    @staticmethod
    def f(arg1, arg2, ...):
        ...

以上实例声明了静态方法 f,从而可以实现实例化使用 C().f(),当然也可以不实例化调用该方法 C.f()。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class C(object):
    @staticmethod
    def f():
        print('runoob');
 
C.f();          # 静态方法无需实例化
cobj = C()
cobj.f()        # 也可以实例化后调用


#输出结果:
runoob
runoob

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

汀、人工智能

十分感谢您的支持

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

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

打赏作者

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

抵扣说明:

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

余额充值