2017-06-15 42 views
1

我试图通过python脚本执行在文本文件中写入的SQL命令。但是,如果任何SQL命令失败,python脚本会抛出错误并停止执行中间的文本文件。结果是几乎没有执行这些命令,只剩下很少的命令。如何在python中获取异常后继续读取txt文件

我期待我的代码抛出错误,并继续在文本文件中执行其余的命令。

我阅读代码:

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将被丢弃并抛出异常。

+3

为什么不直接使用'DROP TABLE ... IF EXISTS'呢? –

回答

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

在单行上使用'executecript'有点矫枉过正。如果只使用'execute',代码更易读(因为它更好地表示实际操作)。 – JohanL

+0

此外,您应该在打开文件的同时使用'with',或者至少在'for'循环后关闭它。 (你可能知道这一点,但其他人在这里阅读可能会错过它。) – JohanL

+0

感谢您的帮助。我会记住提及的要点。 – newbie

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() 

这将导致每个有问题的行报告错误,但随后在下一行continnue执行。

+0

感谢它的工作。 – newbie

+0

但你接受了其他答案? :-) – JohanL

+0

两者都在工作:-) – newbie