【问题标题】:Assign values from SQL Server procedure to variable in c#?将值从 SQL Server 过程分配给 C# 中的变量?
【发布时间】:2015-12-18 22:27:05
【问题描述】:

这是我在 Microsoft Visual Studio ASP.NET MVC4 中使用 C# 编写的代码

int numRows = new SqlCommand("execute getRows", con);

错误信息:

不能隐式转换类型 'System.Data.SqlClient.SqlCommand' 到 'int'

我错过了一步吗?比如我必须做ExecuteReader() 之类的事情吗?

我找不到在 ASP.NET MVC 4 中使用 SQL 命令的好资源。

我知道不要使用 SQL 注入的字符串连接 b/c,所以我正在尝试使用 SQL Server 存储过程。

程序如下:

CREATE PROCEDURE getRows
AS
BEGIN
    select COUNT(*) 
    from myTable 
    where Status = 1
END

注意:我尝试过使用(int)Int.Parse 进行投射。我认为这与阅读有关吗?还是让 getRows 程序有输出?

【问题讨论】:

  • ExecuteScalar() 在这种情况下会为您提供帮助。
  • 是的,有效!谢谢

标签: c# sql sql-server stored-procedures type-conversion


【解决方案1】:

还有一点complicated:

SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;

cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;

sqlConnection1.Open();

int numRows = (int)cmd.ExecuteScalar();

sqlConnection1.Close();

More 信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多