必须声明表变量@table

时间:2012-12-22 13:31:42

标签: c# sql console-application

我是C#和SQL的初学者,我有这个我要执行的SQL插入语句。它要求我想插入的其他变量中的表名。

但是,当我运行此控制台应用程序时,我收到此错误:

  

必须声明表变量@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);                
}

3 个答案:

答案 0 :(得分:12)

你不能这样做。您不能像以下那样将表名作为参数传递:

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);                    

...

答案 1 :(得分:5)

表名不能是sql查询中的输入参数。但是,您始终可以“在将sql字符串传递给SqlCommand之前准备它,如下所示:

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

然后

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

答案 2 :(得分:1)

试试这个......

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