4

Python爬虫编程思想(83):用Python操作SQLite数据库

 2 years ago
source link: https://blog.csdn.net/nokiaguy/article/details/121347827
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Python爬虫编程思想(83):用Python操作SQLite数据库

        通过sqlite3模块[1]中提供函数可以操作SQLite数据库,sqlite3模块是Python语言内置的,不需要安装,直接导入该模块即可。

        sqlite3模块中提供了丰富的函数可以对SQLite数据库进行各种操作,不过在对数据进行增、删、改、查以及其他操作之前,先要使用connect函数打开SQLite数据库,通过该函数的参数指定SQLite数据库的文件名即可。打开数据库后,通过cursor方法获取sqlite3.Cursor对象,然后通过sqlite3.Cursor对象的execute方法执行各种SQL语句,如创建表、创建视图、删除记录、插入记录、查询记录等。如果执行的是查询SQL语句(SELECT语句),那么execute方法会返回sqlite3.Cursor对象,需要对该对象进行迭代,才能获取查询结果的值。

        下面的例子使用connect函数在当前目录创建了一个名为data.sqlite的SQLite数据库,并在该数据库中建立了一个persons表,然后插入了若干条记录,最后查询persons表的所有记录,并将查询结果输出到控制台。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK