Must declare the table variable @table

不想你离开。 提交于 2019-11-27 15:13:40

You can't do this. You can't pass the table name as a parameter the way you did:

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

You can do this instead:

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

...

The table name cannot be an input parameter in a sql query. However, you can always "prepare the sql string BEFORE passing it to the SqlCommand as follows:

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

and then

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

Try this...

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!