[英]Why doesn't this INSERT command work?
我的系統沒有任何錯誤,但是當我嘗試添加時,沒有添加任何內容到tblHardware。 這是我的代碼。
private void btnTilfoj_Click(object sender, EventArgs e)
{
conn = new SqlConnection(connectionstring);
conn.Open();
commandstring = "INSERT INTO tblItUdstyr([HardwareType], [KobsDato], [SerieNr]) VALUES(@HardwareType, @KobsDato, @SerieNr)";
comm = new SqlCommand(commandstring, conn);
comm.Parameters.Add("@HardwareType", SqlDbType.VarChar);
comm.Parameters["@HardwareType"].Value = cbHardware.Text.ToString();
comm.Parameters.Add("@KobsDato", SqlDbType.Date);
comm.Parameters["@KobsDato"].Value = dtpKobsDato.Value;
comm.Parameters.Add("@SerieNr", SqlDbType.VarChar);
comm.Parameters["@SerieNr"].Value = txtSerienr.Text.ToString();
}
你需要運行這個:
comm.ExecuteNonQuery();
但是,還有一些我建議做的事情:
using (SqlConnection conn = new SqlConnection(connectionstring))
{
conn.Open();
commandstring = "INSERT INTO tblItUdstyr([HardwareType], [KobsDato], [SerieNr]) VALUES(@HardwareType, @KobsDato, @SerieNr)";
comm = new SqlCommand(commandstring, conn);
comm.Parameters.AddWithValue("@HardwareType", cbHardware.Text.ToString());
comm.Parameters.AddWithValue("@KobsDato", dtpKobsDato.Value);
comm.Parameters.AddWithValue("@SerieNr", txtSerienr.Text.ToString());
comm.ExecuteNonQuery();
}
我添加了using
因為它將正確關閉並處置SqlConnection
。 此外,我添加了AddWithValue
方法,因為它的流線型和類型匹配更准確。
每個命令都應該以某種方式執行。
你的代碼很好,但沒有最后一個電話
使用這樣的東西
commandstring = "INSERT INTO tblItUdstyr([HardwareType], [KobsDato], [SerieNr]) " +
"VALUES(@HardwareType, @KobsDato, @SerieNr)";
using(conn = new SqlConnection(connectionstring))
using(comm = new SqlCommand(commandstring, conn))
{
conn.Open();
comm.Parameters.Add("@HardwareType", SqlDbType.VarChar);
comm.Parameters["@HardwareType"].Value = cbHardware.Text.ToString();
comm.Parameters.Add("@KobsDato", SqlDbType.Date);
comm.Parameters["@KobsDato"].Value = dtpKobsDato.Value;
comm.Parameters.Add("@SerieNr", SqlDbType.VarChar);
comm.Parameters["@SerieNr"].Value = txtSerienr.Text.ToString();
comm.ExecuteNonQuery(); //This is the call that sends your data to the database
}
請注意我是如何將所有代碼放在using語句中的 。 這將在您完成后強制關閉和處理SqlCommand和SqlConnection。 如果有例外情況
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.