gpt4 book ai didi

c# - 从 C# 执行 SQL Server 存储过程

转载 作者:行者123 更新时间:2023-11-30 19:53:09 24 4
gpt4 key购买 nike

我在 C# 控制台应用程序中执行我的存储过程时遇到问题,我不知道问题出在哪里。你能看看吗?

string path="";

StringBuilder sb = new StringBuilder();
StringBuilder sqlErrorMessages = new StringBuilder("Sql Exception:\n");

try
{
SqlConnection conn = new SqlConnection("Data Source=DESKTOP-M3IMRLE\\SQLEXPRESS; Initial Catalog = db2; Integrated security=true");

Console.WriteLine("Enter path : ");
path = Console.ReadLine();
conn.Open();

SqlCommand cmd = new SqlCommand();

SqlCommand command = new SqlCommand("EXECUTE main.mainproc @path='" + path + "'", conn);

if(command!=null)
{
Console.WriteLine("JSON loaded");
}

conn.Close();
}
catch(SqlException ex)
{
sqlErrorMessages.AppendFormat("Message: {0}\n", ex.Message);
}

最佳答案

您可以执行存储过程,将其名称指定给 SqlCommand 构造函数并将 CommandType 标记为存储过程。
参数加载到命令的 Parameters 集合中:

SqlCommand cmd = new SqlCommand("mainproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@path", SqlDbType.NVarChar).Value = path;
cmd.ExecuteNonQuery();

ExecuteNonQuery 的最终调用运行您的存储过程,但它适用于运行 INSERT/UPDATE 或 DELETE 命令的过程,或者换句话说,不返回数据的命令。

如果您的存储过程需要返回一条或多条记录,那么您需要更多代码:

....
SqlDataReader reader = cmd.ExecuteReader();

while(reader.Read())
{
// Get data from the first field of the current record assuming it is a string
string data = reader[0].ToString();
}

ExecuteReader 方法通过 Read 调用开始检索您的数据,然后继续直到有记录要读取。在循环中,您可以检索索引读取器实例的字段数据(并将对象值转换为适当的类型)

关于c# - 从 C# 执行 SQL Server 存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50519158/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com