I am trying to write to a database from c#:
using (SqlConnection connection = new SqlConnection())
{
try
{
connection.ConnectionString = "Data Source=nesoi;Initial Catalog=SalesDWH;Integrated Security=True";
// This creates an object with which you can execute sql
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = @"INSERT INTO [SalesDWH].[dbo].[PendingSpecimens]
([Date Entered]
,[Specimen ID]
,[Test]
,[Agency])
VALUES (@DateEntered,@SpecimenID,@Test,@Agency)";
command.CommandType = CommandType.Text;
// This is how you add a parameter to your sql command
// This way you are protected against SQL injection attacks
SqlParameter DateEntered = command.CreateParameter();
DateEntered.ParameterName = "@DateEntered";
DateEntered.Value = fields[0];
command.Parameters.Add(DateEntered);
SqlParameter SpecimenID = command.CreateParameter();
SpecimenID.ParameterName = "@SpecimenID";
SpecimenID.Value = fields[1];
command.Parameters.Add(SpecimenID);
SqlParameter Test = command.CreateParameter();
Test.ParameterName = "@Test";
Test.Value = fields[2];
command.Parameters.Add(Test);
SqlParameter Agency = command.CreateParameter();
Agency.ParameterName = "@Agency";
Agency.Value = fields[4];
command.Parameters.Add(Agency);
connection.Open();
int someint=command.ExecuteNonQuery();
}
}
catch(Exception ee)
{
textBox1.Text = ee.ToString();
}
In addition to no errors being returned, it has not written anything either!
What am I doing wrong?
I suspect that this line:
command.ExecuteNonQuery();
is not working.
Mut I do not understand why
please help!
Try this:
Maybe you are missing the parentheses in the values clause?