mysql与python交互

fetchone()和fetchone()用法
cs1.fetchone() # 返回一条结果行,结果为元组,需要解包
cs1.fetchall()  # 接收全部的返回结果行,结果为元组,需要解包
cs1.execute(sql)  # 执行sql语句
爬虫项目代码
注意{}外也有‘’,注意categoryMovieTable无引号,注意value('{}', '{}', '{}', '{}')
fetchone()  # 返回一条结果,没有返回None
fetchall()  # 返回所有结果,没有返回空元组,不是None
class CategoryPipeline(object):
    def process_item(self, item, spider):
        if spider.name == 'category':
            sql = "select count(*) from categoryMovieTable where title='{}'".format(item.get('title'))
            sql1 = "insert into categoryMovieTable(category, url, title, source) value('{}', '{}', '{}', '{}')".format(item.get('category'), item.get('url'), item.get('title'), item.get('source'))
            put_to_mysql(sql, sql1)
        return item
python链接mysql代码
from pymysql import *

def main():
    # 创建Connection连接
    conn = connect(host='localhost',port=3306,database='jing_dong',user='root',password='mysql',charset='utf8')
    # 获得Cursor对象
    cs1 = conn.cursor()
    # 执行insert语句,并返回受影响的行数:添加一条数据
    # 增加
    count = cs1.execute('insert into goods_cates(name) values("硬盘")')
    #打印受影响的行数
    print(count)
    count = cs1.execute('insert into goods_cates(name) values("光盘")')
    print(count)

    # 更新
    count = cs1.execute('update goods_cates set name="机械硬盘" where name="硬盘"')
    # 删除
    count = cs1.execute('delete from goods_cates where id=6')

    # 提交之前的操作,如果之前已经之执行过多次的execute,那么就都进行提交
    conn.commit()
	
	# 执行select语句,并返回受影响的行数:查询一条数据,查询不需要conn.commit()操作
    count = cs1.execute('select id,name from goods where id>=4')
    
    # 关闭Cursor对象
    cs1.close()
    # 关闭Connection对象
    conn.close()

if __name__ == '__main__':
    main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值