2016-05-20 107 views
0

如何在下面的语句如何使用声明的ExecuteScalar声明

this.OpenConnection(); 
SqlParameter[] SqlParameters = {new SqlParameter("@a",A)}; 
return Convert.ToLong( SqlHelper.ExecuteScalar((SqlConnection)DatabaseConnection, "StoredprocName",SqlParameters).ToString()); 
+0

为什么'SqlHelper'管理打开连接? – Crowcoder

回答

0

下面是一个例子从MSDN添加using语句添加,希望这将有助于:

static public int AddProductCategory(string newName, string connString) 
{ 
    Int32 newProdID = 0; 
    string sql = 
     "INSERT INTO Production.ProductCategory (Name) VALUES (@Name); " 
     + "SELECT CAST(scope_identity() AS int)"; 
    using (SqlConnection conn = new SqlConnection(connString)) 
    { 
     SqlCommand cmd = new SqlCommand(sql, conn); 
     cmd.Parameters.Add("@Name", SqlDbType.VarChar); 
     cmd.Parameters["@name"].Value = newName; 
     try 
     { 
      conn.Open(); 
      newProdID = (Int32)cmd.ExecuteScalar(); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
     } 
    } 
    return (int)newProdID; 
} 

更多的SqlCommand。 ExecuteScalar方法():https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx

+0

我无法在这里初始化数据库连接,它已在其他一些库中初始化。 –

+0

我刚刚发现,您可能无法像在代码中显示的那样使用sqlHelper。以下是有关sqlHelper的MSDN信息: _This API支持产品基础结构,不能直接在您的代码中使用._ https://msdn.microsoft.com/zh-cn/library/system.data。 linq.sqlclient.sqlhelpers(v = vs.110)的.aspx – YouneS