简体   繁体   中英

Insert row into SQL Server with C# Winforms

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) 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`

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