TableName as parameter? (asp.net, c#)

  • Thread starter Thread starter Kruno Milicevic
  • Start date Start date
K

Kruno Milicevic

I want to fill DataGrid with some table from my database. I usual use
something like this:

string sqlString ="SELECT * FROM TableName";
OleDbCommand myOleDbCommand = new OleDbCommand(sqlString , OleDbConn);
OleDbDataAdapter myOleDbDataAdapter = new OleDbDataAdapter();
myOleDbDataAdapter.SelectCommand=myOleDbCommand;
DataSet myDataSet=new DataSet();
myOleDbDataAdapter.Fill(myDataSet);
DataGrid1.DataSource = myDataSet;
DataGrid1.DataBind();

And it works, but now i want to use TableName like parameter so that i can
use shown code for different TableName-s. Because of that i made few simple
changes:

string sqlString ="SELECT * FROM @TableName ";

OleDbCommand myOleDbCommand = new OleDbCommand(sqlString , OleDbConn);

myOleDbCommand.Parameters.Add("@TableName ",OleDbType.Char);
myOleDbCommand.Parameters["@TableName"].Value=stringTableName;

OleDbDataAdapter myOleDbDataAdapter = new OleDbDataAdapter();
myOleDbDataAdapter.SelectCommand=myOleDbCommand;
DataSet myDataSet=new DataSet();
myOleDbDataAdapter.Fill(myDataSet);
DataGrid1.DataSource = myDataSet;
DataGrid1.DataBind();

And somewhere else i define stringTableName and depending on this value i
should get different tables (tables with name=stringTableName) shown in
DataGrid1. But it doesnt work!!! I get for this line

myOleDbDataAdapter.Fill(myDataSet);

error message:

Syntax error in query. Incomplete query clause.

It seems that error is in my sqlString...
Please help, how to make parameter from TableName?

Thanks.
 
Its not possible to pass TableName as Parameter.
If you are worried about Sql-Injection type of attacks, you need make sure
you Quote the TableName identifier appropriately and escape any special
characters. In .Net Framework version2.0 Beta(CodeNamed Whidbey) you can use
the SqlCommandBuilder.QuoteIdentifier/OleDbCommandBuilder.QuoteIdentifier
method to do this for you. Here is a code snippet.
<Code Snippet>
SqlCommandBuilder sqlcommandbuilder1 = new SqlCommandBuilder();
String string1 = sqlcommandbuilder1.QuoteIdentifier("Test;Select 1=1;"); //
"returns [Test;Select 1=1;]"
</Code Snippet>
 
Back
Top