在python中获取异常后如何继续读取txt文件

2024-04-25 05:17:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试通过python脚本执行在文本文件中编写的SQL命令。但是如果任何SQL命令失败,python脚本就会抛出错误并停止执行中间的文本文件。结果是执行的命令很少,剩下的命令也很少。你知道吗

我希望我的代码抛出错误并继续执行文本文件中的其余命令。你知道吗

我的阅读代码:

import sqlite3 as sqlite
File_Name = input(" please provide text file name : ")
DB_Name = input (" Please provide the Database Name : ")
connection = sqlite.connect(DB_Name)
cursor = connection.cursor()

Text_File = open (File_Name,'r')
Text = Text_File.read()
Text_File.close()
try:
    cursor.executescript(Text)
except sqlite.Error as e:
    print ("sql command error  ",e)
connection.commit()
connection.close() 

文本文件类似于:

drop table test_p;
drop table test_p1;
drop table test_p2;

create table test_p(a number );
create table test_p1(a number );
create table test_p2(a number );

insert into test_p values(1);
insert into test_p values(2);
insert into test_p1 values(3);
insert into test_p1 values(4);
insert into test_p2 values(5);
insert into test_p2 values(6);

这里,如果表test\u p1不存在,并且我正在运行脚本,那么test\u p将被删除,并引发异常。你知道吗


Tags: textnametest命令脚本sqlitetableconnection
2条回答

正如注释中指出的,对于特定的错误,可以使用IF EXISTS来避免它。在一般情况下,您可以循环输入并在每一行上使用execute,而不是executescript

import sqlite3 as sqlite
File_Name = input(" please provide text file name : ")
DB_Name = input (" Please provide the Database Name : ")
connection = sqlite.connect(DB_Name)
cursor = connection.cursor()

with open (File_Name,'r') as file:
    for line in file:
        try:
            cursor.execute(line)
        except sqlite.Error as e:
            print ("sql command error  ",e)

connection.commit()
connection.close()

这将导致每个有问题的行报告一个错误,然后在下一行继续执行。你知道吗

您可以按1:1读取并执行文件中的行:

for line in open(File_Name,'r'):
    try:
        cursor.executescript(line)
    except sqlite.Error as e:
        print ("sql command error  ", e)

相关问题 更多 >