System.Data.SqlServerCe.SqlCeException'在System.Data.SqlS
本文关键字:System Data SqlS SqlServerCe SqlCeException | 更新日期: 2023-09-27 17:51:18
当我尝试执行这段代码时,会导致一个错误。
我的要求得到最新插入的增量id
_connection.Open();
cmd.Connection = _connection;
cmd.CommandText = "Insert into Finalresult(Section_name, userId, examid) Select Section_name, User_id, Exam_id from result" +
"WHERE (User_id = '" + userid + "' Exam_id='" + examis + "' And Section_name='" + section + "')SELECT SCOPE_IDENTITY()";
Int32 newId = (Int32)cmd.ExecuteScalar();
行出现错误Int32 newId = (Int32)cmd.ExecuteScalar();
错误是
类型为"System.Data.SqlServerCe"的异常。SqlCeException'在System.Data.SqlServerCe.dll中发生,但未在用户代码中处理
这里需要进行一些更改,例如添加错误处理。要了解异常背后的原因,您需要检查异常的Errors
属性:
try
{
//Your code here
}
catch (SqlCeException e)
{
foreach (SqlCeError error in e.Errors)
{
//Error handling, etc.
MessageBox.Show(error.Message);
}
}
这样做,它会告诉你错误是什么。
我认为你的User_id
和Exam_id
'参数'在SQL语句中被视为字符串,因为你用单引号包围它。据猜测,这将是您的问题,以及WHERE子句中缺少逻辑运算符。
但是不要这样做参数化!当您以这种方式连接查询时,您将自己暴露于SQL注入攻击。MSDN上有很多关于如何做到这一点的文章和信息,或者看看Jeff Atwood的文章- http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/
好吧,为了进一步细分,根据marc_s的评论,您不能在SQL CE中使用SCOPE_IDENTITY()
。所以你要这样做:
参数化插入:
var sqlString = "Insert into Finalresult(Section_name, userId, examid) Select Section_name, User_id, Exam_id from result " +
"WHERE (User_id = @userId AND Exam_id = @examId AND Section_name = @sectionName"
cmd.CommandText = sqlString;
cmd.Parameters.Add("@userId", userid);
cmd.Parameters.Add("@examId", examId);
cmd.Parameters.Add("@sectionName", section);
cmd.ExecuteNonQuery();
然后在相同的连接上(当然是不同的命令),获得插入的id:
cmd.Connection = _connection;
cmd.CommandText = "SELECT @@identity";
Int32 newId = (Int32)cmd.ExecuteScalar();
我还没有测试或编译这个,所以只是把它作为一个想法/指导
如果userid,Examids是整型,则不要使用单引号。
cmd.CommandText = "Insert into Finalresult(Section_name, userId, examid) Select Section_name, User_id, Exam_id from result" +
" WHERE (User_id = " + userid + " Exam_id=" + examis + " And Section_name='" + section + "')SELECT SCOPE_IDENTITY()";
您的查询有错误。试试这个:
cmd.CommandText = "Insert into Finalresult(Section_name, userId, examid) Select Section_name, User_id, Exam_id from result" +
" WHERE (User_id = '" + userid + "' AND Exam_id='" + examis + "' And Section_name='" + section + "')SELECT SCOPE_IDENTITY()";