我正在尝试通过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 将被删除并引发异常。
最佳答案
您可以逐一读取并执行文件中的行:
for line in open(File_Name,'r'):
try:
cursor.executescript(line)
except sqlite.Error as e:
print ("sql command error ", e)
关于python - 如何在Python中出现异常后继续读取txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44560972/