在尝试将字符串“09/21/3013”插入ArrivalDate列(即smalldatetime)之前,我已将所有内容插入正常。我如何转换这个,以便我可以插入数据库?提前谢谢!
以下是代码:
private void ExecuteInsert(string BookingName, string BookedBy)
{
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["CateringAuthorizationEntities"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string sql = "INSERT INTO tbBooking (BookingName, BookedBy, ArrivalDate) VALUES "
+ " (@BookingName, @BookedBy, @ArrivalDate)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
//param[0] = new SqlParameter("@id", SqlDbType.Int, 20);
param[0] = new SqlParameter("@BookingName", System.Data.SqlDbType.VarChar, 50);
param[1] = new SqlParameter("@BookedBy", System.Data.SqlDbType.VarChar, 50);
param[2] = new SqlParameter("@ArrivalDate", System.Data.SqlDbType.SmallDateTime);
param[0].Value = BookingName;
param[1].Value = BookedBy;
param[2].Value = ArrivalDate;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void BtnCatering_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//call the method to execute insert to the database
ExecuteInsert(BookingName.Text, BookedBy.Text);
Response.Write("Record was successfully added!");
}
}
答案 0 :(得分:1)
if (ArrivalDate != DBNull.Value)
param[2].Value = Convert.ToDateTime(ArrivalDate);
else
{
param[2].Value = // default value
}
答案 1 :(得分:0)
您可以尝试使用DateTime而不是String。
param[2].Value = Convert.ToDateTime(ArrivalDate);
答案 2 :(得分:0)
使用DateTime.ParseExact
可以控制日期的确切转换:
CultureInfo provider = CultureInfo.InvariantCulture;
param[2].Value = DateTime.ParseExact(ArrivalDate, "MM/dd/yyyy hh:mm:ss tt", provider);