必须声明表变量@table(Must declare the table variable @tab

2019-07-17 12:31发布

我在C#和SQL初学者,我有我要执行此SQL INSERT语句。 它要求我要插入其它变量之间的表名。

但是,当我运行这个控制台应用程序,我得到这个错误:

必须声明表变量@table

这是代码的一部分:

StreamReader my_reader =  getFile(args);
string CS = formCS();
try
{
    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlCommand com = new SqlCommand("insert into @table (time, date, pin) values (@time, @date, @pin)", con);                    
        con.Open();
        Console.WriteLine("Enter table name:");
        Console.Write(">> ");
        string tblname = Console.ReadLine();
        com.Parameters.AddWithValue("@table", tblname);

        string line = "";
        int count = 0;
        while ((line = my_reader.ReadLine()) != null)
        {
            Dictionary<string, string> result = extractData(line);                        
            com.Parameters.AddWithValue("@time", result["regTime"]);
            com.Parameters.AddWithValue("@date", result["regDate"]);
            com.Parameters.AddWithValue("@pin", result["regPin"]);
            count += com.ExecuteNonQuery();
            com.Parameters.Clear();                        

        }
        Console.WriteLine("Recoreds added : {0}", count.ToString());
        Console.WriteLine("Press Enter to exit.");
    }
    Console.ReadLine();
}
catch (SqlException ex)
{
    Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);                
}

Answer 1:

你不能做到这一点。 你无法通过表名作为参数,你所做的一切:

SqlCommand com = new SqlCommand("insert into @table ...");
...
com.Parameters.AddWithValue("@table", tblname);

你可以这样做,而不是:

Console.WriteLine("Enter table name:");
Console.Write(">> ");
string tblname = Console.ReadLine();

string sql = String.Format("insert into {0} (time, date, pin) values ... ", tblname);

SqlCommand com = new SqlCommand(sql, con);                    

...


Answer 2:

表名不能在一个SQL查询的输入参数。 但是,您可以随时“它传递给SqlCommand如下之前准备SQL字符串:

var sqlString = string.Format("insert into {0} (time, date, pin) values (@time, @date, @pin)", tblname) 

然后

SqlCommand com = new SqlCommand(sqlString);
...


Answer 3:

试试这个...

string tblname = "; DROP TABLE users;";
var sqlString = string.Format("insert into {0} (time, date, pin) values (@time, @date, @pin)", tblname)

https://en.wikipedia.org/wiki/SQL_injection



文章来源: Must declare the table variable @table