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연락처를 추가합니다.의 2가지 파라미터sp_Add_contact(@FirstName,@LastName)구글에서 몇 가지 좋은 예를 검색해봤지만 재미있는 것은 없었다.
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모든 일회용 객체가 올바르게 폐기되도록 합니다.
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)
기능적인 면에서는 차이가 없습니다.그들이 추천하지 않은 이유는
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();
}
}
}
또 다른 방법으로는 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
위의 스토어드 프로시저는 국가명(@COUNTERY VARCHAR(20))을 파라미터로 받아들여 입력 국가에서 모든 퍼블리셔를 반환합니다.명령어가 실행되면유형이 StoredProcedure로 설정되어 있습니다.파라미터 컬렉션을 사용하여 파라미터를 정의할 수 있습니다.
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();
}
}
}
여기 제가 공유하고 싶은 기술이 있습니다.clr 속성 유형이 bool -> bit, long -> bigint, string -> nchar/varchar/nvarchar, decimal -> money와 같은 SQL 대응 유형이면 잘 작동합니다.
public void SaveTransaction(Transaction transaction)
{
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
{
using (var cmd = new SqlCommand("spAddTransaction", con))
{
cmd.CommandType = CommandType.StoredProcedure;
foreach (var prop in transaction.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
cmd.Parameters.AddWithValue("@" + prop.Name, prop.GetValue(transaction, null));
con.Open();
cmd.ExecuteNonQuery();
}
}
}
언급URL : https://stackoverflow.com/questions/7542517/call-a-stored-procedure-with-parameter-in-c-sharp
'programing' 카테고리의 다른 글
| SQL Server - INSERT 후 값 반환 (0) | 2023.04.06 |
|---|---|
| SQL Server : 컬럼에서 행으로 (0) | 2023.04.06 |
| 스토어드 프로시저에서 "SET XACT_ABORT ON"을 사용하면 어떤 이점이 있습니까? (0) | 2023.04.06 |
| 쿼리를 사용하여 임시 테이블에 데이터 삽입 (0) | 2023.04.06 |
| DELETE 문에서 별칭을 사용할 수 없는 이유는 무엇입니까? (0) | 2023.04.06 |