python - 如何在Python中出现异常后继续读取txt文件

标签 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 将被删除并引发异常。

最佳答案

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

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/

相关文章:

基于文本文件字符串的Python条件语句

python - Google 电子钱包服务器是否会对每次订阅续订进行回调?

python - Python 中的 Perl 正则表达式

java - 数据库错误: "NullPointerException: Attempt to invoke virtual method getApplicationInfo()... on a null object reference"

mysql - 删除...左加入sqlite中的查询

sqlite 搜索多列

python - 在 tensorflow 2.0 中获取变量范围

python - 如果月份 = 十月、十一月或十二月,则从年份中减去 -1,否则年份 python

node.js - Sequelize hasMany 加入关联

bash - Bash:如何在sqlite3中插入具有特殊字符的文本?