簡體   English   中英

如何將行值從sql server轉換為c#中的字符串

[英]how to convert row value from sql server to string in c#

我有這樣的方法

private string AccountCreation()
{
     string accountId="";

     using (SqlConnection connection = new SqlConnection(ConnectionString))
     {
         connection.Open();
         SqlCommand command = new SqlCommand();
         command.Connection = connection;
         StringBuilder sql = new StringBuilder();
         sql.AppendLine("SELECT ACCOUNT_ID,CUSTOMER_ID FROM T_ACCOUNT order by ACCOUNT_ID desc");
         sql.AppendLine("SET IDENTITY_INSERT T_ACCOUNT ON");
         sql.AppendLine("INSERT INTO  T_ACCOUNT (ACCOUNT_ID,CUSTOMER_ID)");
         sql.AppendLine("SELECT ACCOUNT_ID + 1, CUSTOMER_ID +1 FROM T_ACCOUNT Where ACCOUNT_ID = (select max(ACCOUNT_ID) from T_ACCOUNT)");
         sql.AppendLine("SET IDENTITY_INSERT T_ACCOUNT OFF");
         accountId = Convert.ToString(sql.AppendLine("SELECT top 1 ACCOUNT_ID FROM T_ACCOUNT order by ACCOUNT_ID desc"));
         string strUpdateQuery = sql.ToString();
         ExecuteQuery(strUpdateQuery, command);                
     }
     return accountId;
}

現在accountId保留查詢,但不保存查詢執行后返回的值。 我想要該字符串中的值。 誰能幫我?

從查詢中獲取價值。 您需要ExecuteScalar方法。

object oRetVal = command.ExecuteScalar();
string accountId = string.Empty;

if(oRetVal != null) 
{
    accountId = oRetVal.ToString();
}

但是,建議使用store procedure

我假設您正在從查詢中尋找“ TOP 1 Account_ID”。 您在那里所做的一切將無法工作(或給您您想要的)。 您將需要發送一個輸出參數以輸入accountID,或者使用datareader或dataset運行獲取數據。

您必須將ExecuteQuery的輸出綁定到對象。 檢查是否返回任何結果並填充accID。

var accID = ExecuteQuery(strUpdateQuery, command)

public string ExecuteQuery(string query,SqlCommand cmd)
{
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = query;
    object i=cmd.ExecuteScalar();
    return i.ToString();
}

之后,只需將其分配給

accountId = ExecuteQuery(strUpdateQuery, command);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM