gpt4 book ai didi

c# - 为 tableName 创建参数导致异常

转载 作者:行者123 更新时间:2023-11-30 20:56:33 26 4
gpt4 key购买 nike

您好,我正在尝试创建一个通用方法来从数据库中读取数据。这是我目前所拥有的:

private static void GetData(string tableName, string key, string values)
{
string connectionString = "data source=DB03RO;initial catalog=NCOI_Dev;User ID=NCOI_Olympus;Password=Olympus;persist security info=False;packet size=4096;Enlist=true;Transaction Binding=Explicit Unbind;";
string commandText = @"SELECT @key , @value FROM @Name";
SqlDataReader reader = null;

using (var connection = new SqlConnection(connectionString))
using (var cmd = new SqlCommand())
{
connection.Open();
cmd.Connection = connection;
cmd.Parameters.Add(new SqlParameter("@Name", tableName));
cmd.Parameters.Add(new SqlParameter("@key", key));
cmd.Parameters.Add(new SqlParameter("@value", values));
cmd.CommandType = CommandType.Text;
cmd.CommandText = commandText;
reader = cmd.ExecuteReader();

while (reader != null)
{
string id = (string)reader[key];
string data = (string)reader[values];
Console.WriteLine(id + " " + data);
}
}
}

当我尝试执行读取器时,我似乎遇到了错误:

Must declare the table variable "@Name".

我该如何解决这个问题?

最佳答案

您不能用参数化查询替换数据库对象(表、列、 View 等)名称。您只能通过连接来完成。

string commandText = String.Format("SELECT {0}, {1} FROM {2}", key, value, tableName);

关于c# - 为 tableName 创建参数导致异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17466381/

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