简体   繁体   中英

Why doesn't this INSERT command work?

My system does not come with any errors, but there is not added anything to tblHardware when I try to add. This is my code.

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();
}

You need to run this:

comm.ExecuteNonQuery();

However, there are some other things I'd recommend doing:

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();
}

I added the using because that will properly close and dispose the SqlConnection . Further, I added the AddWithValue method because it's streamlined and more accurate as far as type matching.

Every command should be executed in some way.
Your code is fine, but lacks of the last call

Use something like this

 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
}

Notice how I have put all your code inside a using statement . This will enforce the closing and disposing of the SqlCommand and SqlConnection after you have finished. Also in case of exceptions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM