Van*_*alk 5 c# sql sql-server string save
我正在尝试将SQL结果放在C#字符串变量或字符串数组中.可能吗?我需要以某种方式使用SqlDataReader吗?我是C#函数的新手,以及以前在PHP中工作的所有函数,所以如果可以,请提供一个工作示例(如果相关我已经可以连接并访问数据库,插入并选择..我只是不知道如何将结果存储在字符串变量中).
小智 6
这不是历史上最好的一个例子,好像你没有从数据库中返回任何行,你最终会遇到异常,但是如果你想使用数据库中的存储过程,而不是运行一个SELECT语句直接从你的代码,然后这将允许你返回一个字符串:
public string StringFromDatabase()
{
SqlConnection connection = null;
try
{
var dataSet = new DataSet();
connection = new SqlConnection("Your Connection String Goes Here");
connection.Open();
var command = new SqlCommand("Your Stored Procedure Name Goes Here", connection)
{
CommandType = CommandType.StoredProcedure
};
var dataAdapter = new SqlDataAdapter { SelectCommand = command };
dataAdapter.Fill(dataSet);
return dataSet.Tables[0].Rows[0]["Item"].ToString();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
它肯定可以改进,但是如果你想要沿着存储过程路线运行它会给你一个起点.
| 归档时间: |
|
| 查看次数: |
63084 次 |
| 最近记录: |