SQL Insert Query Using C#

后端 未结 8 1785
长情又很酷
长情又很酷 2020-11-27 17:24

I\'m having an issue at the moment which I am trying to fix. I just tried to access a database and insert some values with the help of C#

The things I tried (worked)

8条回答
  •  无人及你
    2020-11-27 18:10

    I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...
    here is the code from my current project:

    public static int ParametersCommand(string query,List parameters)
    {
        SqlConnection connection = new SqlConnection(ConnectionString);
        try
        {
            using (SqlCommand cmd = new SqlCommand(query, connection))
            {   // for cases where no parameters needed
                if (parameters != null)
                {
                    cmd.Parameters.AddRange(parameters.ToArray());
                }
    
                connection.Open();
                int result = cmd.ExecuteNonQuery();
                return result;
            }
        }
        catch (Exception ex)
        {
            AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
            return 0;
            throw;
        }
    
        finally
        {
            CloseConnection(ref connection);
        }
    }
    
    private static void CloseConnection(ref SqlConnection conn)
    {
        if (conn.State != ConnectionState.Closed)
        {
            conn.Close();
            conn.Dispose();
        }
    }
    

提交回复
热议问题