c# - 如何从 C# 聊天机器人与机器人应用程序在 SQL Server 中执行存储过程?
问题描述
这是 SQL 查询:
CREATE PROCEDURE get_nearest_Restaurants
@lat FLOAT,
@lng FLOAT
AS
BEGIN
DECLARE @point GEOMETRY
SET @point = GEOMETRY::Point(@lat, @lng, 4326)
SELECT TOP (5)
Id, Name, City, @point.STDistance(Location) AS Location
FROM
[dbo].[Restaurants]
ORDER BY
@point.STDistance(Location)
END
GO
解决方案
您可以使用SqlCommand
来引用您的StoredProcedure
,然后使用 获取数据SqlDataAdapter
。
不要忘记传递参数SqlParameter
。
get_nearest_Restaurants
此代码将在您的 BotApplication 中调用您的 sp ( ):
public async Task<DataTable> ExecuteSp(string lat, string lng)
{
SqlConnection cnn = new SqlConnection("Data Source=ServerName/IP;Initial Catalog=DatabaseName;User ID=UserName;Password=Password");
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
try
{
cnn.Open();
cmd = new SqlCommand("get_nearest_Restaurants", cnn);
cmd.Parameters.Add(new SqlParameter("@lat", lat));
cmd.Parameters.Add(new SqlParameter("@lng", lng));
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
await Task.FromResult(da.Fill(dt));
}
catch (Exception)
{
}
finally
{
cnn.Close();
cmd.Dispose();
}
return dt;
}
要连接到SQL-Server
您应该使用SqlConnection
. 中有一个属性SqlConnection
,即ConnectionString
,它定义了我们的位置SQL-Server
以及我们如何连接到它。
推荐阅读
- c# - 如何使用 nUnit、Selenium 计算 DOM 元素中的元素?
- java - SpringData JPA 本机查询提供 java.sql 数据而不是 LocalDate
- button - 在 1602 LCD 上滚动文本,同时聆听按钮按下
- bash - 如何从 Heroku 为单个 bash 命令设置环境变量,而不是为整个 shell 会话设置环境变量?
- python - 如何使用循环和命令输出的if条件
- python - 如何使用flask/python从sql表中获取
- swt - jface TreeViewer 的滚动锁定
- python - flask sqlalchemy 将数据库名称作为字符串传递
- electron - 如何在电子应用程序中包含模板组件的分布
- python-3.x - 在 Pandas 中查找目录中的总文件大小