【pyhton】连接数据库及带参数插入数据

前言

最近做项目要把新闻的标题,内容,链接提取出来,放入数据库。花了2天半的时间弄这个,踩了一些坑,记录下来。

pymysql连接数据库
# 打开数据库连接
        db = pymysql.connect("47.107.41.60","root","密码","wisdomagriculture"
        )
        # 使用cursor()方法获取操作游标
        cursor = db.cursor()
        for content in content_list:
            print("*"*50)
            # print("title"+content["title"])
            title = content["title"]
            href = content["href"]
            # print("0"+href[0])
            # print("1"+title[0])

            sql = "INSERT INTO news (news_title,news_href,news_time) VALUES (%(title)s,%(href)s,%(time)s)"
            print(content)
            cursor.execute(sql,content)
            db.commit()
        db.close()

注意:

  • 在插入数据的时候一定要注意,不要插入list[]类型的。
  • 在插入字典类型的数据的时候,可以这么写。
			sql = "INSERT INTO news (news_title,news_href,news_time) VALUES (%(title)s,%(href)s,%(time)s)"
            cursor.execute(sql,content)
  • 最后要提交一下
  • 正则获取数据的时候
            href = re.findall(r"<a href='(.*?)'", content, re.S)[0] if len(re.findall(r"<a href='(.*?)'", content, re.S))>0 else '错误'


职场就像方便面,曲曲折折,三分钟热度,关键是加量不加价。

原创文章 73 获赞 79 访问量 33万+

猜你喜欢

转载自blog.csdn.net/qq_41346335/article/details/89191815