Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

c# - MySqlParameter as TableName

I want to use MySqlParameter to pass tableName into query (to prevent slq injections)

MySqlCommand cmd = new MySqlCommand("select * from @table"), cn)
cmd.Parameters.AddWithValue("@table",TableName);

But this is not working. How can I pass tableName as parameter

P.S. I tried to change @ to ? - not working

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot pass table name as parameter. You have to use dynamic SQL to do this, so you have to string concentration to do it, for example

  MySqlCommand cmd = new MySqlCommand(String.Format("select * from {0}",tableName), cn)

But because users input the tableName, so SQL injection is possible. You can use this SQL to determine if that table exists before query anything from it:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'tablename';

(You can perfectly parametrize this query, so SQL injection will be eliminated)

Generally, be careful of SQL injection. But if you use this internal (not expose to user), then SQL injection should not be problem.

Better, you can construct a stored procedure to deal with this, as in my another answer:

Unified SQL getter with LINQ


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...