【发布时间】:2010-06-18 06:51:34
【问题描述】:
我有以下问题。
我有一个带有一些 DateTime 属性的对象,以及一个存储所有对象的数据库表,在 Sql server 中我想将 DateTime 属性存储在 DateTime 数据类型的某些列中,但是 sql server 中 datetime 的格式是与 c# 中的 DateTime 类不同,我得到一个 sql 异常,说“无法解析 DateTime”。我知道如何通过制作 yyyy-MM-dd 格式来解决这个问题,但这是正确和最佳的解决方案吗?
public void UpdateInvitation(string ownerId, string couponKey, string status, string invitedEmail, DateTime? sentDate, DateTime? redeemedDate)
{
using (var con = new SqlConnection(this.ConnectionString))
{
try
{
con.Open();
var command =
new SqlCommand(
"UPDATE INVITATIONS SET Status='@status', InvitedEmail='@invitedEmail', SentDate='@sentDate', RedeemDate='@redeemedDate' WHERE CouponKey='@CouponKey' AND OwnerId='@OwnerId'");
var ownerIdParam = new SqlParameter("@ownerId", ownerId);
var couponKeyParam = new SqlParameter("@couponKey", couponKey);
var statusParam = new SqlParameter("@status", status);
var invitedEmailParam = new SqlParameter("@invitedEmail", invitedEmail);
var sentDateParam = new SqlParameter("@sentDate", sentDate.Value) { SqlDbType = SqlDbType.DateTime };
var redeemedDateParam = new SqlParameter("@redeemedDate", redeemedDate.Value) { SqlDbType = SqlDbType.DateTime };
command.Parameters.AddRange(new[]
{
ownerIdParam, couponKeyParam, statusParam, invitedEmailParam,
sentDateParam, redeemedDateParam
});
command.Connection = con;
var rowsAffected = command.ExecuteNonQuery();
Log.DebugFormat("Invitation updated for owner id : [{0}] with key {1}, {2} rows affected", ownerId,
couponKey, rowsAffected);
}
catch (Exception exception)
{
throw new InvitationDataContextException(exception);
}
}
}
【问题讨论】:
-
你能不能。你正在使用的代码?尤其是您在代码中使用的 SQL 语句。
-
你能粘贴你用过的代码吗?
标签: c# sql database sql-server-2005 datetime