Saturday, August 2, 2014

Insert Into Statement Crashes

Hello,


I would highly recommend that parameters are used when constructing your SQL statement.


MSDN Configuring parameters. The example below is simple and the parameter types are string but that at least provides something to go by. Look at the chart of the link above to create each of your parameters. Lastly look at the AddWithValue method of the parameter collection.



private void DemoInsert(string FirstName, string LastName)
{
int Affected = 0;
using (SqlConnection cn = new SqlConnection { ConnectionString = "Your connection string goes here" })
{
using (SqlCommand cmd = new SqlCommand
{
CommandText = "INSERT INTO SomeTable (FirstName,LastName) VALUES (@FirstName,@LastName)", Connection = cn})
{
cmd.Parameters.Add(new SqlParameter { ParameterName = "@FirstName", DbType = DbType.String, Value = FirstName });
cmd.Parameters.Add(new SqlParameter { ParameterName = "@LastName", DbType = DbType.String, Value = LastName });

cn.Open();

Affected = cmd.ExecuteNonQuery();
if (Affected == 1)
{
// Success
}
else
{
// Failed
}
}
}
}





Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.


No comments:

Post a Comment