Insert C# data.sqlclient

Asked

Viewed 71 times

0

good afternoon!

I’m starting in C# and I have a question

ja varios tipo de Insert sql server. Ai I’m having difficulty in this part

says: it is not possible to convert from "system.data.sqlclient.sqlparameter"

follows the code:

string strSQL = @"INSERT INTO TESTE (Razão_Social) VALUES ( @parm1 )";
            conn.Open();
            SqlCommand cmd = new SqlCommand (strSQL, conn);
            cmd.Parameters.AddWithValue(@parm1, txt_razao.Text);
            cmd.ExecuteNonQuery();
            conn.Close();



            MessageBox.Show("Cadastrado !!!!");

1 answer

0


The method AddWithValue receives two parameters: (string, object), according to the documentation: Addwitvalue

So it must be like this:
cmd.Parameters.AddWithValue("@parm1", txt_razao.Text);

Taking advantage, to help control and close your command object, place your code in a block using, thus:

conn.Open();
string strSQL = @"INSERT INTO TESTE (Razão_Social) VALUES ( @parm1 )";
using(SqlCommand cmd = new SqlCommand(strSQL, conn))
{
   cmd.Parameters.AddWithValue("@parm1", txt_razao.Text);
   cmd.ExecuteNonQuery();
}
  • thanks solved, or doubt? because I have to use in sqlcommand?

  • this would give an answer :) I do not know if you know the concept of Dispose, not knowing this question explains well: https://answall.com/q/70839/57220 basically, objects that use resources like files, network connections among others, need to free these resources, close the files, connections, etc... for example the SqlCommand, has the method Close for this.. to facilitate these operations, some classes implement the interface IDisposable, which requires you to implement the Dispose, where resources are generally released...

  • To make the job easier, and to avoid having to always call this method, was to create the command using (do not confuse with the using at the beginning of the file where you have the references of the used namespaces). The using automatically executes the method Dispose when you finish, that is, when you finish your block in closing keys } he will execute the cmd.Close() and everything else it takes to release the features of the problem, simple and clean, and great if you forget to do it :) Only works with objects that implement the IDisposible, the SqlConnection also for example

  • I hope term explained well, any questions just ask, and tb has other questions about it here on the site :)

  • For, I understood nice agr! , however one doubt the Sqlconnection.close would not solve the situation ?

  • yes solve, can even put it in a block of using tbm :)

  • thanks. I close by. Very good explanation !!!!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.