Inserting Data With C# and parameterized values


/ Published in: C#
Save to your folder(s)

Not that theres anything new to this. In fact its very old fashioned, but If you like me forget how its done; snip it.


Copy this code and paste it in your HTML
  1. using System.Data;
  2. using System.Data.SqlClient;
  3. using System.Configuration;
  4. var connectionStr = ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString;
  5. SqlCommand cmd = new SqlCommand();
  6. cmd.Connection = new SqlConnection(CONNECTIONSTR);
  7. cmd.Parameters.Add(new SqlParameter("@name", name));
  8. cmd.Parameters.Add(new SqlParameter("@lastName", lastName));
  9. cmd.Parameters.Add(new SqlParameter("@date",DateTime.Now));
  10. cmd.Connection.Open();
  11. cmd.CommandText =
  12. "INSERT INTO myTable (email, bannerType, score, name, lastName, date) " +
  13. "VALUES (@email, @bannerType, @score, @name, @lastName, @date)";
  14.  
  15. var rowsAffected = cmd.ExecuteNonQuery();
  16. cmd.Connection.Close();
  17. cmd.Connection.Dispose();
  18. return rowsAffected;

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.