如何在C#中调用SQL代码

时间:2021-03-06 15:06:32

I have two classes in which the teachers have merged their final projects into one, one class is software engineering and another one is data bases. The thing is that for SE i have to develop a desktop/smartphone app and for DB i have to develop every DB related stuff for that app.

我有两个班级,老师们将他们的最终项目合并为一个,一个是软件工程,另一个是数据库。问题是,对于SE,我必须开发桌面/智能手机应用程序,对于数据库,我必须为该应用程序开发每个数据库相关的东西。

But i have to keep both things separated, i mean i have to keep C# code away from SQL code so i can't do queries or any stuff using selection strings and such, i just have to call stored procedures with said queries from code.

但我必须保持两个事物分离,我的意思是我必须保持C#代码远离SQL代码,所以我不能使用选择字符串等进行查询或任何东西,我只需要使用代码中的所述查询来调用存储过程。

Any idea how could i do that? To summarize i just want to call any code or procedure that i write in sql and store it's values in a variable,object or array.

知道我怎么能这样做?总结一下,我只想调用我在sql中编写的任何代码或过程,并将其值存储在变量,对象或数组中。

As i said i cannot use:

正如我所说我不能使用:

string selectstr = "SELECT * FROM students;"

and execute that query, i have to write that in sql and call it from C# and store the values returned.

并执行该查询,我必须在sql中编写它并从C#调用它并存储返回的值。

1 个解决方案

#1


1  

Stored procedures are called like any other SQL command in C#:

与C#中的任何其他SQL命令一样,调用存储过程:

using (SqlCommand cmd = new SqlCommand("MyStoredProcedure", connection))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@myParameter1", value);
    ...

    using (SqlDataReader reader = cmd.ExecuteReader())
    {
       ...
    }
}

The "magic" bit is to set the command type correctly ;-)

“魔术”位是正确设置命令类型;-)

#1


1  

Stored procedures are called like any other SQL command in C#:

与C#中的任何其他SQL命令一样,调用存储过程:

using (SqlCommand cmd = new SqlCommand("MyStoredProcedure", connection))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@myParameter1", value);
    ...

    using (SqlDataReader reader = cmd.ExecuteReader())
    {
       ...
    }
}

The "magic" bit is to set the command type correctly ;-)

“魔术”位是正确设置命令类型;-)