2016-11-29 52 views
-2

我試圖在數據庫表中插入今天的日期。但問題是今天的日期而不是這個值「1900-01-01」被插入到數據庫中。我使用的是SQL Server 2012的錯誤的日期插入到SQL Server 2012中

ASP.NET標記:

<asp:TextBox ID="msnDate" runat="server" Enabled="false"></asp:TextBox> 
<cc1:CalendarExtender ID="msnDate_CalendarExtender" runat="server" Enabled="True" TargetControlID="msnDate"> 
</cc1:CalendarExtender> 

代碼隱藏我寫了這個代碼:

msnDate_CalendarExtender.SelectedDate = DateTime.Today; 

這是插入查詢

protected void btnSave_Click(object sender, EventArgs e) 
{ 
    SqlConnection cs = new SqlConnection("Data Source=DESKTOP-3T94FQ0;Initial Catalog=RAMS;Integrated Security=False;UID=sa;Password=sa123;"); 
    SqlCommand cmd = new SqlCommand("INSERT INTO [tbl_musannet] ([pessenger_id],[mus_date]) VALUES('"+ ddlPessengerList.Text + "','" + msnDate.Text +"')", cs); 
    cs.Open(); 
    cmd.ExecuteNonQuery(); 
    cs.Close(); 
} 
+0

我沒有在這裏找到任何插入查詢,顯示查詢,而不是爲asp代碼 –

+0

謝謝你添加了插入查詢。 – bluebay

+0

您是否嘗試過'msnDate_CalendarExtender.SelectedDate'而不是'msnDate.Text';注意注入 –

回答

0

您正在使用日期的字符串表示形式而未明確設置格式,這意味着它可以根據Culture ASP.NET應用程序的設置以及數據庫服務器的設置。

(例如是05/06/11 2011年6月5日,或2011年5月6日,或2005年6月?11日)

也有潛在的SQL注入的問題太多。您可以通過使用參數將這兩個問題解決在一起,這些參數會將原始日期時間值(而不是格式化表示)傳遞到數據庫服務器,其中不存在歧義。

Int32 pessengerId; 
if(!Int32.TryParse(ddlPessengerList.Text, out pessengerId)) { 
    // abort, show error message 
    return; 
} 

DateTime msnDate = msnDate.Value; // your `msnDate` control should have a strongly-typed way of getting the raw DateTime value, you should not attempt to parse a textual representation of a date/time. 
if(msnDate < new DateTime(2016, 01, 01)) { 
    // sanity-check the date range, if it's too far in the past or future reject it, according to your business rules 
    return; 
} 

SqlCommand cmd = cs.CreateCommand(); 
cmd.CommandText = "INSERT INTO tbl_musannet (pessenger_id, mus_date) VALUES(@passengerId, @musDate)"; 
cmd.Parameters.AddWithValue("@pessenger_id", pessengerId); 
cmd.Parameters.AddWithValue("@musDate ", msnDate); 

cs.Open(); 
cmd.ExecuteNonQuery(); 
cs.Close() 
+0

好的。謝謝。我正在嘗試這個。 – bluebay

+0

你應該看看[我們可以停止使用AddWithValue()了嗎?](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/)並停止使用'.AddWithValue()' - 它可能會導致意想不到的結果... –

相關問題