我试图通过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将被丢弃并抛出异常。
为什么不直接使用'DROP TABLE ... IF EXISTS'呢? –