您应该在存储过程中执行此操作。这将基本上格式化和存储您的查询。您设置从代码传入的参数,然后读出结果。
例子:
C#方法:
private void SetNote()
{
const string sql = "sp_SelectControllerNoteByID";
using (var conn = MocSystem.GetMocDbConnection())
{
using (var comm = new SqlCommand(sql, conn))
{
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter("@ControllerNoteID", ControllerNoteId));
try
{
conn.Open();
using (var rdr = comm.ExecuteReader())
{
while (rdr.Read())
{
CommentText = rdr["NoteText"].ToString();
_commentor = new User(new Guid(rdr["NoteAuthor"].ToString()));
CommentDate = (DateTime)rdr["NoteDate"];
MocRequestId = (int)rdr["MocRequestID"];
}
}
}
catch (Exception ex)
{
HasError = true;
ErrorMessage += "\nThere was a problem building the note: " + ex.Message;
}
}
}
}
DBMS(本例中为sql server)上的存储过程:
ALTER proc [dbo].[sp_SelectControllerNoteByID]
@ControllerNoteID int
AS
SELECT
ControllerNoteID,
NoteText,
NoteDate,
NoteAuthor,
MocRequestID
FROM
ControllerNotes
WHERE
ControllerNoteID = @ControllerNoteID
所以这里我们调用存储过程,在这种情况下它只是一个简单的选择语句,然后我们通过 ADO 将它读入一个对象。现在,通过这种方式,您可以修改查询而无需重新编译。除非您添加参数,否则您还必须在代码中更新这些参数。