Python使用sqlite插入数据无效的原因

本文介绍了一种常见爬虫问题的解决方案:为何爬取的数据未能成功存入SQLite数据库。通过调整代码逻辑,确保数据库连接正确并在每次插入数据后及时提交更改。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


使用爬虫时,将数据爬下来之后进行插入操作,但是查看数据库的时候发现并没有任何数据插入。查看被插入数据的格式和内容时机都已经被抓下来了,搜索了很久没有找到答案,最终还是在stackoverflow上面找到了答案,教训就是:


要学会用英文搜索Google!!!


要学会用stackoverflow!!!


Google大法好,stackoverflow大法好!!!


代码如下:


# -*- coding: utf-8 -*-

import urllib,urllib2,re,time,thread,sqlite3,string

class Spider_Model:

    def __init__(self):
        self.page = 1
        self.pages = []
        self.enable = False
        self.conn = None
        self.cursor = None
        
    def GetPage(self,page):
        myUrl = "http://m.byr.cn/board/ParttimeJob"+"?p="+page
        user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'   
        headers = { 'User-Agent' : user_agent }   
        req = urllib2.Request(myUrl, headers = headers)
        myResponse = urllib2.urlopen(req)
        myPage = myResponse.read()
        unicodePage = myPage.decode("utf-8")

        myItems = re.findall('<li.*?><div><a href="(.*?)">(.*?)</a>',unicodePage,re.S)
        items = []
        for item in myItems:
            if not item[0].find('class')>=0:
                items.append([item[0],item[1]])
        return items

    def LoadPage(self):
        while self.enable:
            if len(self.pages)<2:
                try:
                    myPage = self.GetPage(str(self.page))
                    self.page += 1
                    self.pages.append(myPage)
                except BaseException,e:
                    print e

                else:
                    time.sleep(1)

    def ShowPage(self,nowPage,page):
        self.conn = sqlite3.connect('123.db')
        self.cursor = self.conn.cursor()
        self.cursor.execute('create table if not exists forum_data (id INTEGER primary key UNIQUE, title varchar(20), attr varchar(20))')
        
        for items in nowPage:
            if page<=3:
                attr = items[0].split('ParttimeJob/')
                article_id = string.atoi(attr[1])
                article_title = items[1]
                article_attr = 'http://m.byr.cn/article/ParttimeJob/'+attr[1]
                self.cursor.execute("insert into forum_data (id ,title, attr) values (?, ?, ?)",(article_id, article_title, article_attr))
                self.conn.commit()
                print u'第%d页' %page,article_id, article_title, article_attr
            else:
                self.cursor.close()
                self.conn.close()
                self.enable = False
                break

    def Start(self):
        self.enable = True
        page = self.page

        print u'正在加载请稍后'
        
        thread.start_new_thread(self.LoadPage,())

        while self.enable:
            if self.pages:
                nowPage = self.pages[0]
                del self.pages[0]
                self.ShowPage(nowPage,page)
                page += 1


           



print u'请按下回车浏览今日的论坛内容:'    
raw_input(' ')    
myModel = Spider_Model()    
myModel.Start() 
                

    
                
                                 
        


1、在类中的函数要使用初始化的函数中的对象时,要在前面加self.conn,self.cursor。


2、在每次插入数据后,要使用self.commit进行提交,而不是最后一并在提交,只有close是在最后一次使用。

<think>我们使用SQLite数据库时,经常需要查询最新插入数据。通常可以通过以下方式实现:1.如果表中有一个自增的主键(例如id),那么最新插入数据id值最大,我们可以按id降序排列取第一条。2.如果表中没有自增主键,但有时间戳字段,那么我们可以按时间戳降序排列取第一条。3.如果两者都没有,可能需要重新设计表结构,因为无法可靠地确定插入顺序。根据引用[2]中的示例,表结构是未知的。假设有一个自增的字段(例如id)或者时间戳字段(例如create_time),我们可以这样操作。**方法1:使用自增主键字段(推荐)**假设表中有一个自增的主键字段,如`id`,那么查询最新的一条记录:```pythonimportsqlite3#连接数据库conn=sqlite3.connect('your_database.db')cursor=conn.cursor()#执行查询,按id降序排列并取第一条cursor.execute("SELECT*FROMyour_tableORDERBYidDESCLIMIT1;")latest_record=cursor.fetchone()print("最新记录:",latest_record)#关闭连接conn.close()```**方法2:使用时间戳字段**如果表中有一个记录插入时间的字段(如`created_at`),那么可以按这个字段降序排列取第一条:```pythoncursor.execute("SELECT*FROMyour_tableORDERBYcreated_atDESCLIMIT1;")```**注意**:-如果表中有多个记录可能同时插入(时间相同),则可能无法准确获取最新记录。此时可以结合自增主键。-如果表没有这样的字段,建议添加一个自增主键或者时间戳字段以确保可以追踪插入顺序。**示例代码(假设表名为`user_table`,有自增主键`user_id`):**```pythondefget_latest_record():conn=sqlite3.connect("student.db")cursor=conn.cursor()try:cursor.execute("SELECT*FROMuser_tableORDERBYuser_idDESCLIMIT1;")record=cursor.fetchone()ifrecord:print("最新记录:",record)else:print("表中没有数据")exceptsqlite3.Errorase:print(f"查询失败:{e}")finally:conn.close()```**重要提示**:确保表中有可以确定插入顺序的字段,否则这种方法将无效。§§相关问题§§1.如何向SQLite表中添加自增主键字段?2.如何记录数据插入时间戳?3.如果表中没有自增字段也没有时间戳,如何获取最后插入数据?4.SQLite中如何创建包含自增主键的表?</think> ### 如何使用PythonSQLite查询最新插入数据Python使用SQLite查询最新插入数据,可以通过以下两种常用方法实现。核心思路是利用SQL语句的排序和限制功能: #### 方法1:使用自增主键(推荐) 如果表中包含自增主键(如 `id` 列),按主键降序获取第一条: ```python import sqlite3 def get_latest_record(): conn = sqlite3.connect("student.db") cursor = conn.cursor() try: # 按id降序排序,取第一条记录 cursor.execute("SELECT * FROM user_table ORDER BY id DESC LIMIT 1;") result = cursor.fetchone() if result: print("最新记录:", result) else: print("表中没有数据") except sqlite3.Error as e: print("查询失败:", e) finally: conn.close() ``` #### 方法2:使用时间戳字段 如果表中包含插入时间戳(如 `created_at` 列): ```python def get_latest_by_timestamp(): conn = sqlite3.connect("student.db") cursor = conn.cursor() try: # 按时间戳降序排序,取第一条 cursor.execute("SELECT * FROM user_table ORDER BY created_at DESC LIMIT 1;") result = cursor.fetchone() if result: print("最新记录:", result) else: print("表中没有数据") finally: conn.close() ``` #### 关键说明: 1. **排序依据**: - `ORDER BY field DESC` 对指定字段降序排列 - `LIMIT 1` 限制只返回第一条结果 2. **注意事项**: - 确保表中有可排序的字段(自增ID或时间戳) - 如果表结构未知,可通过 `PRAGMA table_info(user_table);` 查看字段 - 使用参数化查询防止SQL注入(示例中无变量故未使用) 3. **替代方案**: ```sql SELECT * FROM user_table WHERE id = last_insert_rowid(); ``` 但此方法只适用于**同连接会话**内获取刚刚插入的记录[^1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值