0

I just started to use SQL Server 2008. I have a winforms application that must insert data from the application into the database and some textbox values could be empty. After googling to search how do that i found something but i would an explanation.

I found this code to insert record into DB (Excluding Connection code)

stringInsert += "INSERT INTO MyDatabase(dateTime, Name, Surname)";
stringInsert += "VALUES(@Date, @NameString, @SurnameString)";

SqlCommand cmd = new SqlCommand(stringInsert, con);

cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("@Date", strTime));
cmd.Parameters.Add(new SqlParameter("@Name", StringName));
cmd.Parameters.Add(new SqlParameter("@Surname", StringSurname));

if (string.IsNullOrEmpty(StringName))
   cmd.Parameters.Add(new SqlParameter("@Name", DBNull.Value.ToString()));
else
   cmd.Parameters.Add(new SqlParameter("@Name", StringName));

But someone else wrote that the method cmd.Parameters.AddWithValue("@Name" , StringName);

do the if else in automatic because if StringName is null or empty it sets DBNull.Value

Now my questions are :

  1. I don't understand how cmd.Parameters.Add(new SqlParameter("@Name", StringName)); modify stringInsert into StringName. The "@Name" it's only a part of the String so maybe the symbol "@" does something that I don't know? Normally I use the @ symbol when I need to exclude escape like this way @"c:\home"

  2. is it correct use cmd.Parameters.AddWithValue("@Name" , StringName); even if the StringName is empty or null?

  3. is this the correct way to submit data into SQL Server DB with many textbox in a WinForm Application?

Thanks

1 Answer 1

2

1) the @Name is a placeholder. You are asking to NET Engine to substitute the @Name placeholder with the value of the same named parameter. (This is different for ADO NET Providers that doesn't support named parameters)
2) When you want to insert a NULL in the database you should use DBNull.Value, so your code should be cmd.Parameters.AddWithValue("@Name" , string.IsNullOrEmpty(StringName) ? DBNull.Value : StringName);
3) Yes, this is the correct way to go. Always use parametrized query. And using statements`

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.