验证SQL在WebMatrix/Razor中是否正确执行?
问题描述:
我想验证我的SQL是否已经正确执行,并且如果不返回错误。验证SQL在WebMatrix/Razor中是否正确执行?
我的代码:
var db = Database.Open("database");
db.Execute("INSERT INTO Users(Username, Email, FirstName, SecondName) VALUES(?,?,?,?)", username, email, firstName, secondName);
而且,你怎么可以标记使用WebMatrix中作为唯一的列?这似乎是一个非常基本的功能,我真的很想念!我想让它使电子邮件和用户名必须是唯一的,但我看不到任何方式来做到这一点?我基本上希望能够测试是否可以执行INSERT INTO(即没有电子邮件/用户名已经存在于数据库中)。
谢谢你的帮助。
答
关于第一个问题:
的Execute
方法返回受影响的记录数,所以如果它失败了,它会返回一个值,它不等于1
var db = Database.Open("database");
if (db.Execute("INSERT INTO Users(Username, Email, FirstName, SecondName) VALUES(?,?,?,?)", username, email, firstName, secondName) < 1)
throw new Exception("Wasn't able to insert User record");
第二,我不确定,但它可能应该在一个单独的问题。
答
我想创建一个存储过程,有条件地添加新用户,并返回一个行数(0,如果用户已经存在):
create procedure dbo.AddUser
@username varchar(80)
, @email varchar(128)
, @firstname varchar(128)
, @secondname varchar(128)
as
insert into [Users] (Username,Email,FirstName,SecondName)
select @username, @email, @firstname, @secondname
where not exists(
select 1 from [Users] (nolock)
where [email protected]
and [email protected]
)
return @@rowcount
go
从C#调用:
var db = Database.Open("database");
if (db.Execute("dbo.AddUser @username=?, @email=?, @firstname=?, @secondname=?", username, email, firstName, secondName) < 1)
throw new Exception("Wasn't able to insert User record");