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 :
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"is it correct use
cmd.Parameters.AddWithValue("@Name" , StringName);even if theStringNameis empty or null?is this the correct way to submit data into SQL Server DB with many textbox in a WinForm Application?
Thanks