【发布时间】:2015-04-14 11:40:12
【问题描述】:
我正在使用sqlite3pp 来操作数据库。当我尝试通过运行在同一个表中插入一条记录两次时,
sqlite3pp::command cmd(db, "INSERT INTO Groups (Name) VALUES (?)");
cmd.binder() << "Group_one";
cmd.execute();
它抛出了一个异常并向我展示了这个:
libc++abi.dylib:以未捕获的类型异常终止 sqlite3pp::database_error: UNIQUE 约束失败:Groups.Name
但我不确定我应该使用什么类型的异常来捕获?我试过了
try {
cmd.execute();
} catch (std::exception& ex) {}
或
try {
cmd.execute();
} catch (sqlite3pp::database_error& ex) {}
或
try {
cmd.execute();
} catch (...) {}
但它们都不起作用。有人能帮我一下吗?谢谢!
这是我的代码:
#include <iostream>
#include "sqlite3pp.h"
int main(int argc, const char * argv[]) {
sqlite3pp::database db("./test.db");
// Create table
db.execute("CREATE TABLE IF NOT EXISTS Groups(" \
"Name TEXT PRIMARY KEY)");
sqlite3pp::command cmd(db, "INSERT INTO Groups (Name) VALUES (?)");
cmd.binder() << "Group_one";
try {
cmd.execute(); // When I run this code twice, the exception is thrown because of UNIQUE constraint.
} catch (std::exception& ex) {
std::cout << "exception: " << ex.what() << std::endl;
}
std::cout << "Done" << std::endl;
return 0;
}
【问题讨论】: