在C#中使用存储过程 [英] Using Stored Procedures in C#

查看:62
本文介绍了在C#中使用存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#开发数据库应用程序.我需要在表上显示数据,现在我已经完成了.但是我的业务逻辑已硬编码到我的代码中.现在,我想继续在我的代码中使用存储过程.我需要做哪些修改.一个简单的步骤列表就足够了:)

I am working on a database application in C#. I had a requirement to display data on a table and I am now done with that. But my business logic is hardcoded to my code. Now I want to go ahead and use Stored procedures with my code. What are the modifications that I need to do. A simple list of steps would be enough :)

SqlConnection myConnection = new SqlConnection("user id=dbblabla;" + 
            "password=1234;server=localhost\\SQLEXPRESS;" + 
            "Trusted_Connection=yes;" + 
            "database=myDB; " + 
            "connection timeout=30");

try
{
    myConnection.Open();
} catch (SqlException excep){
    Console.WriteLine(excep.StackTrace);
}

String selectionQuery = "SELECT * FROM myTable";
SqlDataAdapter myAdapter = new SqlDataAdapter(selectionQuery,myConnection);

DataSet ds = new DataSet();
myAdapter.Fill(ds,"AllInfo");

dataGridSearchOutput.DataSource = ds.Tables["AllInfo"].DefaultView;

我从创建新的SQL命令开始,但是我不确定我使用的是正确的方法.

I started from creating a new SQL command but I am not sure I am using the correct way.

SqlCommand newCommand = new SqlCommand("SELECT * FROM PMInfo");
newCommand.CommandType = CommandType.StoredProcedure;

推荐答案

存储过程

CREATE PROCEDURE addemp
     @eno int,
     @ename varchar(50),
     @edate datetime
AS
  declare @p int

  select @p=count(*) from emp
      where eno=@eno
  if @p=0
     begin
       insert into emp
         values (@eno,@ename,@edate)
     end        
    RETURN

C#代码

    SqlConnection cn = new SqlConnection(@"conn_str");
    SqlCommand cmd = new SqlCommand("addemp", cn);
    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.AddWithValue("@eno", 10);
    cmd.Parameters.AddWithValue("@ename", "Mr.Xyz");
    cmd.Parameters.AddWithValue("@edate", DateTime.Parse("1-1-2002"));

    cn.Open();
    cmd.ExecuteNonQuery();
    cn.Close();

这篇关于在C#中使用存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆