[C#] C #에서 매개 변수를 사용하여 저장 프로 시저 호출

프로그램에서 삭제, 삽입 및 업데이트를 수행 할 수 있으며 데이터베이스에서 생성 된 저장 프로 시저를 호출하여 삽입을 시도합니다.

이 버튼 삽입은 잘 작동합니다.

private void btnAdd_Click(object sender, EventArgs e)
{
        SqlConnection con = new SqlConnection(dc.Con);
        SqlCommand cmd = new SqlCommand("Command String", con);

        da.InsertCommand = new SqlCommand("INSERT INTO tblContacts VALUES (@FirstName, @LastName)", con);
        da.InsertCommand.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
        da.InsertCommand.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;

        con.Open();
        da.InsertCommand.ExecuteNonQuery();
        con.Close();

        dt.Clear();
        da.Fill(dt);
    } 

sp_Add_contact연락처를 추가하기 위해 명명 된 프로 시저를 호출하는 버튼의 시작입니다 . 의 두 매개 변수입니다 sp_Add_contact(@FirstName,@LastName). 좋은 예를 찾기 위해 Google을 검색했지만 흥미로운 것은 없습니다.

private void button1_Click(object sender, EventArgs e)
{
        SqlConnection con = new SqlConnection(dc.Con);
        SqlCommand cmd = new SqlCommand("Command String", con);
        cmd.CommandType = CommandType.StoredProcedure;

        ???

        con.Open();
        da. ???.ExecuteNonQuery();
        con.Close();

        dt.Clear();
        da.Fill(dt);
    }



답변

쿼리를 실행하는 것과 거의 같습니다. 원래 코드에서 명령 객체를 작성하여 cmd변수에 넣고 절대 사용하지 마십시오. 그러나 여기서 대신을 사용합니다 da.InsertCommand.

또한 using모든 일회용 물체에 a 를 사용하여 올바르게 폐기하십시오.

private void button1_Click(object sender, EventArgs e) {
  using (SqlConnection con = new SqlConnection(dc.Con)) {
    using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
      cmd.CommandType = CommandType.StoredProcedure;

      cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
      cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;

      con.Open();
      cmd.ExecuteNonQuery();
    }
  }
}


답변

SP를 실행하는 데 필요하므로 매개 변수를 추가해야합니다.

using (SqlConnection con = new SqlConnection(dc.Con))
{
    using (SqlCommand cmd = new SqlCommand("SP_ADD", con))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@FirstName", txtfirstname.Text);
        cmd.Parameters.AddWithValue("@LastName", txtlastname.Text);
        con.Open();
        cmd.ExecuteNonQuery();
    }
}


답변

cmd.Parameters.Add(String parameterName, Object value)더 이상 사용되지 않습니다. 대신 사용cmd.Parameters.AddWithValue(String parameterName, Object value)

추가 (문자열 parameterName, 객체 값)가 더 이상 사용되지 않습니다. AddWithValue (String parameterName, Object value) 사용

기능면에서는 차이가 없습니다. 그들이 cmd.Parameters.Add(String parameterName, Object value)선호 하지 않는 이유 AddWithValue(String parameterName, Object value)는 더 명확 해지기 때문입니다. 다음은 동일한 MSDN 참조입니다.

private void button1_Click(object sender, EventArgs e) {
  using (SqlConnection con = new SqlConnection(dc.Con)) {
    using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
      cmd.CommandType = CommandType.StoredProcedure;

      cmd.Parameters.AddWithValue("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
      cmd.Parameters.AddWithValue("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;

      con.Open();
      cmd.ExecuteNonQuery();
    }
  }
}


답변

대안으로, 나는 procs로 쉽게 작업 할 수있는 라이브러리를 가지고 있습니다 : https://www.nuget.org/packages/SprocMapper/

SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
    sqlAccess.Procedure()
         .AddSqlParameter("@FirstName", SqlDbType.VarChar, txtFirstName.Text)
         .AddSqlParameter("@FirstName", SqlDbType.VarChar, txtLastName.Text)
         .ExecuteNonQuery("StoredProcedureName");


답변

public void myfunction(){
        try
        {
            sqlcon.Open();
            SqlCommand cmd = new SqlCommand("sp_laba", sqlcon);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.ExecuteNonQuery();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            sqlcon.Close();
        }
}


답변

.NET 데이터 공급자는 데이터 소스에 연결하고 명령을 실행하며 레코드 세트를 반환하는 데 사용되는 많은 클래스로 구성됩니다. ADO.NET의 명령 개체는 다양한 방식으로 SQL 쿼리를 수행하는 데 사용할 수있는 많은 Execute 메서드를 제공합니다.

저장 프로시 저는 하나 이상의 SQL 문이 포함 된 사전 컴파일 된 실행 가능 개체입니다. 대부분의 경우 저장 프로시 저는 입력 매개 변수를 수락하고 여러 값을 반환합니다. 스토어드 프로 시저가이를 승인하도록 작성된 경우 매개 변수 값을 제공 할 수 있습니다. 입력 매개 변수를 승인하는 샘플 저장 프로시 저는 다음과 같습니다.

  CREATE PROCEDURE SPCOUNTRY
  @COUNTRY VARCHAR(20)
  AS
  SELECT PUB_NAME FROM publishers WHERE COUNTRY = @COUNTRY
  GO

위의 저장 프로시 저는 국가 이름 (@COUNTRY VARCHAR (20))을 매개 변수로 사용하고 입력 국가에서 모든 게시자를 반환합니다. CommandType이 StoredProcedure로 설정되면 Parameters 컬렉션을 사용하여 매개 변수를 정의 할 수 있습니다.

  command.CommandType = CommandType.StoredProcedure;
  param = new SqlParameter("@COUNTRY", "Germany");
  param.Direction = ParameterDirection.Input;
  param.DbType = DbType.String;
  command.Parameters.Add(param);

위 코드는 국가 매개 변수를 C # 응용 프로그램에서 저장 프로 시저로 전달합니다.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connetionString = null;
            SqlConnection connection ;
            SqlDataAdapter adapter ;
            SqlCommand command = new SqlCommand();
            SqlParameter param ;
            DataSet ds = new DataSet();

            int i = 0;

            connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword";
            connection = new SqlConnection(connetionString);

            connection.Open();
            command.Connection = connection;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "SPCOUNTRY";

            param = new SqlParameter("@COUNTRY", "Germany");
            param.Direction = ParameterDirection.Input;
            param.DbType = DbType.String;
            command.Parameters.Add(param);

            adapter = new SqlDataAdapter(command);
            adapter.Fill(ds);

            for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                MessageBox.Show (ds.Tables[0].Rows[i][0].ToString ());
            }

            connection.Close();
        }
    }
}


답변