首页 \ 问答 \ 从python sqlite异常中获取更多信息(Getting more info from python sqlite exceptions)

从python sqlite异常中获取更多信息(Getting more info from python sqlite exceptions)

我正在使用python的内置sqlite3数据库模块

在将对象插入我的数据库表时,引发了以下sqlite异常:

"PRIMARY KEY must be unique"

由于每个对象有不同的插入方法,我无法确定它在哪个表中失败:

import sqlite3
...
class SomeObject1:
....
def _insert_some_object1(self, db_object):
        self._cursor.execute('insert into %s values (?,?,?)' % TABLE_NAME,
        (db_oject.v1, db_object.v2, db_object_v3,))

except Exception as e:main()捕获,所以它只是我得到的信息。

我想知道哪个表插入失败,失败的值等等...

sqlite异常中获取最多信息的正确方法是什么?

谢谢


I'm using python's builtin sqlite3 DB module.

While inserting objects to my DB tables, following sqlite exception raised:

"PRIMARY KEY must be unique"

As there are different insert methods for each object, I can't say for sure in which table does it failed:

import sqlite3
...
class SomeObject1:
....
def _insert_some_object1(self, db_object):
        self._cursor.execute('insert into %s values (?,?,?)' % TABLE_NAME,
        (db_oject.v1, db_object.v2, db_object_v3,))

Exception got caught in main() by except Exception as e:, so it's only info I've got.

I would want to know in which table insertion failed, value that failed, etc...

What's the right way to get the most info from sqlite exceptions?

Thanks


原文:https://stackoverflow.com/questions/34530463
更新时间:2022-06-17 15:06

最满意答案

raw_input的返回值是一个字符串,而不是布尔值。 因此,你is not Trueis not False测试,尽管它们有明确的含义,意思不是你想要的意思。 您需要比较HEADER和字符串值。

所以你需要例如这样的代码:

if HEADER.lower() == 'true':

我用tolower()来进行不区分大小写的比较。 您可能还想剥离空白区域:

if HEADER.strip().lower() == 'true':

我相信你可以填写测试来对付你自己。


即使你有一个布尔值,你也不应该使用像is not Trueis False代码。 你应该用以下方法测试真相:

if somebool:

要么

if not somebool:

因为它更可读。


The return value from raw_input is a string and not a boolean. Hence your is not True and is not False tests, although they have well-defined meaning, that meaning is not the meaning that you intend. You need to compare HEADER against string values.

So you would need, for example, code like this:

if HEADER.lower() == 'true':

I used tolower() to effect case-insensitive comparison. You may also want to strip off white space:

if HEADER.strip().lower() == 'true':

I'm sure you can fill in the test against false yourself.


Even if you did have a boolean, you should not use code like is not True or is False. You should test for truth with:

if somebool:

or

if not somebool:

because it is much more readable.

相关问答

更多
  • 它与Python中的运算符优先级有关 (解释者认为你将True与True比较,因为==具有比not优先更高的优先级)。 您需要一些括号来阐明操作顺序: True == (not False) 一般来说, not在没有括号的比较的右侧使用。 但是,我不能想到在某种情况下,您需要使用not比较的右侧。 It has to do with operator precedence in Python (the interpreter thinks you're comparing True to not, sin ...
  • 来自http://docs.python.org/reference/expressions.html#boolean-operations : 在布尔运算的上下文中,以及当控制流语句使用表达式时,以下值将被解释为false:False,None,所有类型的数字零,空字符串和容器(包括字符串,元组,列表,字典) ,套和frozensets)。 所有其他值被解释为真。 我认为你是误会的关键措辞是“被解释为虚假”或“解释为真实”。 这并不意味着任何这些值与True或False完全相同,甚至等于True或Fals ...
  • 像a is b is c链接操作符a is b is c等价于a is b and b is c 。 所以第一个例子是False is False and False is False ,它的计算结果为True and True ,它的计算结果为True 括号会导致一个评估结果与下一个变量进行比较(如您所预期的那样),所以(a is b) is c的结果与(a is b) is c进行比较。 Chaining operators like a is b is c is equivalent to a is ...
  • 我相信你错误地重载了<=和>=运算符。 代替: def __leq__(self, other): # ... def __geq__(self, other): 改为使用它: def __le__(self, other): # ... def __ge__(self, other): 在进行这些更改并在Python 3.4.1中运行后,我得到: >>> a, b = Omega(), Omega(1) >>> (a+a) <= b True >>> (a+a) <= b True >>> (a+a) ...
  • 使用break退出循环: while True: ser = serial.Serial("/dev/ttyUSB0", 4800, timeout =1) checking = ser.readline(); if checking.find(",,,,"): print "not locked yet" else: print "locked and loaded" break True和False行并没有在你的代码中做任 ...
  • raw_input的返回值是一个字符串,而不是布尔值。 因此,你is not True , is not False测试,尽管它们有明确的含义,意思不是你想要的意思。 您需要比较HEADER和字符串值。 所以你需要例如这样的代码: if HEADER.lower() == 'true': 我用tolower()来进行不区分大小写的比较。 您可能还想剥离空白区域: if HEADER.strip().lower() == 'true': 我相信你可以填写测试来对付你自己。 即使你有一个布尔值,你也不应该使 ...
  • 你在最后的else子句中没有返回任何else 。 因此,结果。 def is_sorted(x,i): if i >= len(x): return True elif x[i] <= x[i-1]: return False else: return is_sorted(x,i+1) 演示: >>> def is_sorted(x,i): ... if i >= len(x): ... return True ...
  • 从这里“恢复”的方法是不要让它发生。 也就是说,你总是可以使用bool()类型来再次访问True和False 。 ( bool()总是返回两个布尔单例之一。) 例: >>> bool >>> bool(1) True >>> bool(1) is bool('true') True >>> True = False >>> True False >>> True is False True >>> False is bool() True >>> True = bool(1) > ...
  • 我可以发现代码中存在很多问题 - 在你的函数grid_string_maker(word_block, x, y) ,你总是返回pos_word_vert ,你永远不会返回水平的。 这是因为每次您调用函数时,都会从起始位置开始,而不是从中断位置开始。 另外,你不需要太多ifs,你可以直接使用0,1,2作为索引,而不是使用y-1如果y == 1 ,因为你已经知道y是1, y-1是0等。你应该改变这个函数,把垂直和水平的字符串作为一个元组返回,然后把它们接收到单独的字符串中。 在你的函数中 - find_wor ...
  • >>> print(True and False) False 布尔值的开头有一个大写字母。 我猜你用的是字符串。 您可以使用type(after)检查。 您无需手动划分所有案例以“调试”您的程序。 这不是Python的用途......只需print评估的代码print(after+' and '+late) ,使用类似我的type或使用交互式python控制台来玩。 >>> print(True and False) False Boolean values have a capital letter ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)