【问题标题】:Continue executing sql statements if error found python sqlite3如果发现错误,继续执行 sql 语句 python sqlite3
【发布时间】:2020-10-22 18:27:55
【问题描述】:

我有一个包含 sql 命令的文件,我想执行文件中给出的命令,如果任何命令抛出任何错误,则忽略该错误并执行下一个命令。 这是一个示例文件:

drop table department;
drop table classroom;

create table classroom
    (building       varchar(15),
     room_number        varchar(7),
     capacity       numeric(4,0),
     primary key (building, room_number)
    );

create table department
    (dept_name      varchar(20), 
     building       varchar(15), 
     budget             numeric(12,2) check (budget > 0),
     primary key (dept_name)
    );

例如。如果教室表不存在,那么 drop table 命令将产生错误并且程序将终止。我希望程序继续运行并执行文件中的所有命令。

我面临的问题是create table 命令在多行中,所以我不知道如何执行。

【问题讨论】:

  • 把整个文件读成字符串,用..我觉得是sqlite连接对象上的executescript方法?
  • 为什么使用指定长度的VARCHAR 而被sqlite忽​​略?
  • @OlvinR​​oght 我没有创建这个文件。我目前正在我的大学学习 sql,这是一个练习题,但我不知道该怎么做。
  • @Shawn 执行sql时出错了怎么办?
  • 那你抓住它并做一些回应?

标签: python sql database sqlite


【解决方案1】:

看看sqlite3 manual:

import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
with open('PATH_TO_SQL_FILE', 'r') as fp:
    text = fp.read().split(';')
    for command in text:
       try:
           cur.execute(command)
       except sqlite3.Error:
           pass

【讨论】:

  • 这将如何处理错误?请仔细阅读问题。
  • 哦,我敢打赌。这是你要找的东西吗:stackoverflow.com/questions/36816640/…
  • 不,这不是我想做的。
  • 我更新了答案。你能详细说明为什么这不是你想做的吗?
  • 看问题下的cmets。
【解决方案2】:
import sqlite3

#define connection and cursor
connection = sqlite3.connect ('test_db')
cursor =connection.cursor()


command1 ="""create table classroom
    (building       varchar(15),
    room_number        varchar(7),
    capacity       numeric(4,0),
    primary key (building, room_number)
    )"""

cursor.execute(command1)


command2 ="""create table department
    (dept_name      varchar(20), 
    building       varchar(15), 
    budget             numeric(12,2) check (budget > 0),
    primary key (dept_name)
    )"""
cursor.execute(command2)

【讨论】:

  • 如果你想添加更多的sql语句那么你需要添加更多的命令(command3,command4等)
  • 这仅适用于示例文件。我希望它适用于任何文件。请仔细阅读问题。
  • 我没有关于文件的任何信息我想把文件作为输入然后执行里面给出的sql命令。
  • 另外我认为如果你没有关于文件的任何信息会很困难......例如,如果你想删除一个尚不存在的表......我预计会出现错误消息...
  • 是的会有错误信息,我想捕捉错误然后执行下一条命令
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-18
  • 2010-09-09
  • 2011-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多