writing to sql server from C#, no errors returned

2019-08-26 10:33发布

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!

2条回答
Animai°情兽
2楼-- · 2019-08-26 11:31

Try this:

using (SqlConnection connection = new SqlConnection("Data Source=nesoi;Initial Catalog=SalesDWH;Integrated Security=True"))
{
    string queryString = "INSERT INTO SalesDWH.dbo.PendingSpecimens([Date Entered], [Specimen ID], Test, Agency) VALUES (" + fields[0] + ", " + fields[1] + ", " + fields[2] + ", " + fields[4] + ")";
    SqlCommand command = new SqlCommand(queryString, connection);
    command.Connection.Open();
    command.ExecuteNonQuery();
}
查看更多
放荡不羁爱自由
3楼-- · 2019-08-26 11:34

Maybe you are missing the parentheses in the values clause?

查看更多
登录 后发表回答