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

时间:2017-06-15 07:12:14

标签: python sqlite

我正在尝试通过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_p1不存在且我正在运行脚本,那么test_p将被删除并抛出异常。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

正如评论中所指出的,对于特定错误,可以使用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()

这将导致每个违规行报告错误,但随后继续执行下一行。