How to execute a stored procedure within C# program

前端 未结 13 1669
别跟我提以往
别跟我提以往 2020-11-22 00:10

I want to execute this stored procedure from a C# program.

I have written the following stored procedure in a SqlServer query window and saved it as stored1:

<
相关标签:
13条回答
  • 2020-11-22 00:14

    Calling Store Procedure in C#

        SqlCommand cmd = new SqlCommand("StoreProcedureName",con);
        cmd.CommandType=CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@value",txtValue.Text);
        con.Open();
        int rowAffected=cmd.ExecuteNonQuery();
        con.Close();
    
    0 讨论(0)
  • 2020-11-22 00:19

    By using Ado.net

    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;
    
    namespace PBDataAccess
    {
        public class AddContact
        {   
            // for preparing connection to sql server database   
    
            private SqlConnection conn; 
    
            // for preparing sql statement or stored procedure that 
            // we want to execute on database server
    
            private SqlCommand cmd; 
    
            // used for storing the result in datatable, basically 
            // dataset is collection of datatable
    
            private DataSet ds; 
    
            // datatable just for storing single table
    
            private DataTable dt; 
    
            // data adapter we use it to manage the flow of data
            // from sql server to dataset and after fill the data 
            // inside dataset using fill() method   
    
            private SqlDataAdapter da; 
    
    
            // created a method, which will return the dataset
    
            public DataSet GetAllContactType() 
            {
    
    
    
        // retrieving the connection string from web.config, which will 
        // tell where our database is located and on which database we want
        // to perform opearation, in this case we are working on stored 
        // procedure so you might have created it somewhere in your database. 
        // connection string will include the name of the datasource, your 
        // database name, user name and password.
    
            using (conn = new SqlConnection(ConfigurationManager.ConnectionString["conn"]
            .ConnectionString)) 
    
                    {
                        // Addcontact is the name of the stored procedure
                        using (cmd = new SqlCommand("Addcontact", conn)) 
    
                        {
                            cmd.CommandType = CommandType.StoredProcedure;
    
                        // here we are passing the parameters that 
                        // Addcontact stored procedure expect.
                         cmd.Parameters.Add("@CommandType",
                         SqlDbType.VarChar, 50).Value = "GetAllContactType"; 
    
                            // here created the instance of SqlDataAdapter
                            // class and passed cmd object in it
                            da = new SqlDataAdapter(cmd); 
    
                            // created the dataset object
                            ds = new DataSet(); 
    
                            // fill the dataset and your result will be
                            stored in dataset
                            da.Fill(ds); 
                        }                    
                }  
                return ds;
            }
    }
    
    ****** Stored Procedure ******
    
    CREATE PROCEDURE Addcontact
    @CommandType VARCHAR(MAX) = NULL
    AS
    BEGIN
      IF (@CommandType = 'GetAllContactType')
      BEGIN
        SELECT * FROM Contacts
      END
    END
    
    0 讨论(0)
  • 2020-11-22 00:20
    using (SqlConnection conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI")) {
        conn.Open();
    
        // 1.  create a command object identifying the stored procedure
        SqlCommand cmd  = new SqlCommand("CustOrderHist", conn);
    
        // 2. set the command object so it knows to execute a stored procedure
        cmd.CommandType = CommandType.StoredProcedure;
    
        // 3. add parameter to command, which will be passed to the stored procedure
        cmd.Parameters.Add(new SqlParameter("@CustomerID", custId));
    
        // execute the command
        using (SqlDataReader rdr = cmd.ExecuteReader()) {
            // iterate through results, printing each to console
            while (rdr.Read())
            {
                Console.WriteLine("Product: {0,-35} Total: {1,2}",rdr["ProductName"],rdr["Total"]);
            }
        }
    }
    

    Here are some interesting links you could read:

    • http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson07.aspx
    • http://www.c-sharpcorner.com/UploadFile/dclark/InsOutsinCS11302005072332AM/InsOutsinCS.aspx
    • http://www.codeproject.com/KB/cs/simplecodeasp.aspx
    • http://msdn.microsoft.com/en-us/library/ms171921(VS.80).aspx
    0 讨论(0)
  • 2020-11-22 00:22

    Using Dapper. so i added this i hope anyone help.

    public void Insert(ProductName obj)
            {
                SqlConnection connection = new SqlConnection(Connection.GetConnectionString());
                connection.Open();
                connection.Execute("ProductName_sp", new
                { @Name = obj.Name, @Code = obj.Code, @CategoryId = obj.CategoryId, @CompanyId = obj.CompanyId, @ReorderLebel = obj.ReorderLebel, @logo = obj.logo,@Status=obj.Status, @ProductPrice = obj.ProductPrice,
                    @SellingPrice = obj.SellingPrice, @VatPercent = obj.VatPercent, @Description=obj.Description, @ColourId = obj.ColourId, @SizeId = obj.SizeId,
                    @BrandId = obj.BrandId, @DisCountPercent = obj.DisCountPercent, @CreateById =obj.CreateById, @StatementType = "Create" }, commandType: CommandType.StoredProcedure);
                connection.Close();
            }
    
    0 讨论(0)
  • 2020-11-22 00:25
    using (var conn = new SqlConnection(connectionString))
    using (var command = new SqlCommand("ProcedureName", conn) { 
                               CommandType = CommandType.StoredProcedure }) {
       conn.Open();
       command.ExecuteNonQuery();
    }
    
    0 讨论(0)
  • 2020-11-22 00:28

    This is code for executing stored procedures with and with out parameters via reflection. Do note that the objects property names need to match the parameters of the stored procedure.

    private static string ConnString = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString;
        private SqlConnection Conn = new SqlConnection(ConnString);
    
        public void ExecuteStoredProcedure(string procedureName)
        {
            SqlConnection sqlConnObj = new SqlConnection(ConnString);
    
            SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConnObj);
            sqlCmd.CommandType = CommandType.StoredProcedure;
    
            sqlConnObj.Open();
            sqlCmd.ExecuteNonQuery();
            sqlConnObj.Close();
        }
    
        public void ExecuteStoredProcedure(string procedureName, object model)
        {
            var parameters = GenerateSQLParameters(model);
            SqlConnection sqlConnObj = new SqlConnection(ConnString);
    
            SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConnObj);
            sqlCmd.CommandType = CommandType.StoredProcedure;
    
            foreach (var param in parameters)
            {
                sqlCmd.Parameters.Add(param);
            }
    
            sqlConnObj.Open();
            sqlCmd.ExecuteNonQuery();
            sqlConnObj.Close();
        }
    
        private List<SqlParameter> GenerateSQLParameters(object model)
        {
            var paramList = new List<SqlParameter>();
            Type modelType = model.GetType();
            var properties = modelType.GetProperties();
            foreach (var property in properties)
            {
                if (property.GetValue(model) == null)
                {
                    paramList.Add(new SqlParameter(property.Name, DBNull.Value));
                }
                else
                {
                    paramList.Add(new SqlParameter(property.Name, property.GetValue(model)));
                }
            }
            return paramList;
    
        }
    
    0 讨论(0)
提交回复
热议问题