[英]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.