Python3 sqlite3限制条件查询的操作

桃夭
桃夭
发布时间:2026-10-14| 5人浏览过
原创

本文详细解析Python3中使用sqlite3进行数据库连接、建表、数据插入及查询的完整流程。重点讲解如何正确使用参数化查询防止SQL注入,并针对自增字段起始位置重置提供具体解决方案。文章通过代码示例展示了从基础连接到高级查询的实战技巧,帮助开发者规避常见语法陷阱。

请注意第10、11和24行的代码,这是本文的核心内容。虽然整体逻辑并不复杂,但其中涉及的一些语法细节容易引发困惑,特此记录以便参考。


import json 
import sqlite3
import re
import argparse
def Get(db_file):
  
    conn = sqlite3.connect(db_file)
    cur = conn.cursor()
    print("5555555")
    value1=(60)# this is must be ()
    cur.execute("select * from exception where AGV_ID=(%s)" %(value1))
    #cursor.execute("insert into exception values('%s', '%s','%s' ) " %(start_time ,ID ,infomation))
 
    result= cur.fetchall()
    print("result:",result)
    for i in result:
       print(i)  
    print("******************************888")
  
def get_agv_id(db_file):
  try:
    conn = sqlite3.connect(db_file)
    cur = conn.cursor()
    cur.execute("select * from exception where AGV_ID=51")
    #print( cur.fetchall())
    result= cur.fetchall()
    for i in result:
       print(i)
  except sqlite3.Error,e:
    print(e)
    
if __name__ == '__main__': 
  parser = argparse.ArgumentParser(description='check the information of db')
  #parser.add_argument('-h', '--help', help='Statistics for abnormal information')
  parser.add_argument('-n', '--name', help=' the db of name ')
  args = vars(parser.parse_args())
  db_name = args['name']
  print("db_name:",db_name)
  conn = sqlite3.connect('db_name')
  cursor = conn.cursor()
  Get('fitkits.db')
  get_agv_id('fitkits.db')  
  
  conn.commit()
  conn.close() 
  print('DONE!')
  print("666")

补充说明:Python结合sqlite3的基本操作流程。

连接数据库


import sqlite3 
# 连接数据库(如果不存在则创建)
conn = sqlite3.connect('test.db')
print("Opened database successfully")
 
# 创建游标
cursor = conn.cursor() 
...
 
# 关闭游标
cursor.close()
# 提交事物
conn.commit()
# 关闭连接
conn.close()

创建表


...
# 创建游标
cursor = conn.cursor()
 
# 创建表
sql = 'CREATE TABLE Student(id integer PRIMARY KEY autoincrement, Name varchar(30), Age integer)'
cursor.execute(sql)
 
# 提交事物
conn.commit()
...

插入数据


...
# 创建游标
cursor = conn.cursor()
 
# 插入数据
sql = "INSERT INTO Student(Name, Age) VALUES(\'love\', 22)"
cursor.execute(sql)
 
# 插入数据 2
data = ('love2', 2221) # or ['love2', 2221]
sql = "INSERT INTO Student(Name, Age) VALUES(?, ?)"
cursor.execute(sql, data)
 
# 提交事物
conn.commit()
...

查询数据


...
# 创建游标
cursor = conn.cursor()
 
# 查询数据
sql = "select * from Student"
values = cursor.execute(sql)
for i in values:
 print(i)
 
# 查询数据 2
sql = "select * from Student where id=?"
values = cursor.execute(sql, (1,))
for i in values:
 print('id:', i[0])
 print('name:', i[1])
 print('age:', i[2])
 
# 提交事物
conn.commit()
...

其他操作

自增字段起始位置


# 设置起始值为1
update sqlite_sequence SET seq = 0 where name = '表名';
# 设置全部表起始值为默认值
delete from sqlite_sequence where name='TableName'; --注意表名区分大小写

以上为个人经验总结,旨在为读者提供参考。欢迎大家提出意见或指出未考虑周全之处,如有错误敬请指正。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。