2017-01-09 75 views
1

我想將UserId的返回值從sql查詢存儲到Usersid變量。但我無法獲取該值.FYI UserName是文本。想要在c中存儲sql select語句的返回值#

int usersid; 
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AzureSql"].ToString())) 
using (SqlCommand command = new SqlCommand()) 
{ 
    connection.Open(); 
    command.CommandText = @"Select UserId from [dbo].[User] where username= @username"; 

    command.Parameters.Clear(); 

    command.Parameters.AddWithValue("@username", currentUser.UserName); 
    usersid = (int)command.ExecuteScalar(); 

    command.CommandText = @"INSERT INTO [dbo].[ClientEmailConfirmation] ([JobNumber],[OrderNumber],[UserId]) VALUES 
                (@JobNumber,@OrderNumber,@UserId)"; 
    command.Parameters.Clear(); 
    command.Parameters.AddWithValue("@JobNumber", JobNumberTextBox.Text); 
    command.Parameters.AddWithValue("@OrderNumber", OrderNumberTextBox.Text); 
    command.Parameters.AddWithValue("@UserId", usersid); 
    command.ExecuteNonQuery(); 

} 

我將不勝感激您的幫助 謝謝, 一個

+0

這中回答:[?得到插入行的身份最好的辦法(http://stackoverflow.com/questions/42648/best-way-to-get-identity-of-inserted-row )和[執行插入命令並返回插入的Id在Sql](http://stackoverflow.com/questions/18373461/execute-insert-command-and-return-inserted-id-in-sql) – Adrian

+0

此問題已答覆[獲取插入行的身份的最佳方式?](http://stackoverflow.com/questions/42648/best-way-to-get-identity-of-inserted-row)和[執行插入命令並返回插入的ID Sql](http://stackoverflow.com/questions/18373461/execute-insert-command-and-return-inserted-id-in-sql) – Adrian

回答

1
using (SqlCommand command = new SqlCommand()) 
{ 
    command.Connection = connection; 
    ... 
+0

我不明白這是如何回答這個問題。這如何幫助海報獲得他們詢問的'UserId'? – catfood

+0

@catfood - 它有助於'command.ExecuteScalar();'執行時沒有錯誤。 – Igor

+0

啊。我錯過了那部分。好。你的答案給出瞭解決方案的一部分,Mmcgowa3提供了其餘部分。 – catfood

-1

轉換標量結果詮釋:

  int userId = Convert.ToInt32(command.ExecuteScalar())); 
+0

很抱歉更新了我的答案。 – Mike

0

前言:我回答將二者結合起來以前的答案,並提供一些最佳實踐。

您的原始代碼示例缺少連接(雙打)SqlConnectionSqlCommand的棋子。你需要下面的代碼片段:

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AzureSql"].ToString())) 
using (SqlCommand command = new SqlCommand()) 
{ 
    connection.Open(); 
    command.Connection = connection; 
    // Rest of code here. 
} 

我寧願分配一個空的命令文本親自在的SqlCommand的構造函數的連接。它始終確保將連接分配給SqlCommand。更多的閱讀可以發現here on MSDN

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AzureSql"].ToString())) 
using (SqlCommand command = new SqlCommand("", connection)) 
{ 
    // Do note that you still have to open the connection here. 
    connection.Open(); 
    // Rest of code here. 
} 

假設您的UserId列是整數類型,那麼施放結果應該沒問題。

usersid = (int)command.ExecuteScalar(); 

你應該實例化自己的SqlParameter實例,而不是使用AddWithValue()方法關閉SqlParameterCollection。如果您有數據類型衝突的機會,AddWithValue可能會導致錯誤的類型導致幾個難以診斷問題。如需進一步閱讀,請查看articleMSDN

command.Parameters.Add(new SqlParameter("@username", SqlDbType.VarChar) { Value = currentUser.UserName });